Пример #1
0
 public static XObjectWrapper MakeWrapper(XText obj)
 {
     if (obj is XCData)
         return MakeWrapper((XCData)obj);
     else
         return new XTextWrapper(obj);
 }
Пример #2
0
 private void ProcessXText(XText xtext, StringBuilder sb, bool performReplacements)
 {
     //.NET likes to just drop out some of the formatting, specially the " which becomes normal old double quotes.
     var correctedText = XmlTextEncoder.Encode(xtext.Value);
     var newvalue = performReplacements ? Replace(correctedText) : correctedText;
     sb.Append(newvalue);
 }
 private static XText CalibrateText(XText n)
 {
     if (n.parent == null)
     {
         return n;
     }
     XNode content = (XNode) n.parent.content;
     while (true)
     {
         content = content.next;
         XText text = content as XText;
         if (text != null)
         {
             do
             {
                 if (content == n)
                 {
                     return text;
                 }
                 content = content.next;
             }
             while (content is XText);
         }
     }
 }
Пример #4
0
 public Service(XElement baseElement, Product parent)
 {
     _nameAndRev = baseElement.Elements(_ns + "span").Nodes().OfType<XText>().FirstOrDefault();
       _amountSpan = baseElement.Elements(_ns + "span").Elements(_ns + "span").Nodes().OfType<XText>().ToList();
       _options = new List<Option>();
       Product = parent;
 }
 public XText(XText other)
 {
     if (other == null)
     {
         throw new ArgumentNullException("other");
     }
     this.text = other.text;
 }
Пример #6
0
                //[Variation(Priority = 3, Desc = "Adjacent text nodes II. (sanity)")]
                public void AdjacentTextNodes2()
                {
                    XText t1 = new XText("a");
                    XElement e = new XElement("root", "hello");
                    e.Add(t1);

                    VerifyOrder(e.FirstNode, t1, -1);
                }
Пример #7
0
                //[Variation(Priority = 3, Desc = "Adjacent text nodes I. (sanity)")]
                public void AdjacentTextNodes1()
                {
                    XText t1 = new XText("a");
                    XText t2 = new XText("");
                    XElement e = new XElement("root", t1, t2);

                    VerifyOrder(t1, t2, -1);
                }
Пример #8
0
        static string EscapeXml(object obj)
        {
            if (obj == null)
            {
                return("");
            }
            var escaped = new System.Xml.Linq.XText(obj.ToString()).ToString();

            return(escaped);
        }
Пример #9
0
 public void Test_text_node()
 {
     var tx = new XText("This is some text");
     var e1 = new XElement("Root", tx);
     var d1 = new XDocument(e1);
     var di = d1.GetObjectId();
     var id = e1.GetObjectId();
     var ti = tx.GetObjectId();
     var d2 = XNodeAnnotationSerializer.Serialize(d1);
     var d3 = XNodeAnnotationSerializer.Deserialize(d2);
     Assert.IsTrue(d3.Root.FirstNode.GetObjectId() == ti);
 }
Пример #10
0
 private void ReplaceFields()
 {
     var elements = DocumentContent.XPathSelectElements( @"//text:text-input[ @text:description = 'Template']",
                                                         Manager );
     var nodes = elements.ToList();
     foreach( var element in nodes )
     {
         var attribute = element.Value;
         var preparedAttribute = attribute.Replace( "U+10FFFD", "@" );
         var text = new XText( preparedAttribute );
         element.ReplaceWith( text );
     }
 }
Пример #11
0
        private void CreateControlFlowFromComment( XElement comment )
        {
            var row = comment.XPathSelectElement( "./ancestor::table:table-row", Manager );
            var commentValue = comment.Value.Replace( "U+10FFFD", "@" );

            var beforeNode = new XText( commentValue + "{" );

            var afterNode = new XText( "}" );

            row.AddBeforeSelf( beforeNode );
            row.AddAfterSelf( afterNode );
            comment.Remove();
        }
Пример #12
0
        public void NodeTypes()
        {
            XDocument document = new XDocument();
            XElement element = new XElement("x");
            XText text = new XText("text-value");
            XComment comment = new XComment("comment");
            XProcessingInstruction processingInstruction = new XProcessingInstruction("target", "data");

            Assert.Equal(XmlNodeType.Document, document.NodeType);
            Assert.Equal(XmlNodeType.Element, element.NodeType);
            Assert.Equal(XmlNodeType.Text, text.NodeType);
            Assert.Equal(XmlNodeType.Comment, comment.NodeType);
            Assert.Equal(XmlNodeType.ProcessingInstruction, processingInstruction.NodeType);
        }
Пример #13
0
	/// <summary>
	/// Encodes a string for use in an XML element or attribute.
	/// </summary>
	/// <param name="value" this="true">The value to encode in XML compatible way.</param>
	/// <returns>The XML encoded string.</returns>
	public static string XmlEncode(this string value)
	{
		Guard.NotNull(() => value, value);

		var output = new StringBuilder();
		var text = new XText(value);

		using (var writer = XmlWriter.Create(output, new XmlWriterSettings { ConformanceLevel = ConformanceLevel.Fragment }))
		{
			text.WriteTo(writer);
			writer.Flush();
			return output.ToString();
		}
	}
Пример #14
0
 /// <summary>
 /// Write as C# code.
 /// </summary>
 private static void WriteAsCode(XText text, CommentSection section, bool inCode)
 {
     var lineNo = 0;
     var content = text.Value;
     if (string.IsNullOrEmpty(content))
         return;
     foreach (var part in content.Split('\n'))
     {
         if ((lineNo > 0) && inCode)
             section.WriteLine();
         section.Write(part.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;"));
         lineNo++;
     }
 }
Пример #15
0
                //[Variation(Desc = "NodeTypes")]
                public void NodeTypes()
                {
                    XDocument document = new XDocument();
                    XElement element = new XElement("x");
                    XText text = new XText("text-value");
                    XComment comment = new XComment("comment");
                    XProcessingInstruction processingInstruction = new XProcessingInstruction("target", "data");

                    Validate.IsEqual(document.NodeType, XmlNodeType.Document);
                    Validate.IsEqual(element.NodeType, XmlNodeType.Element);
                    Validate.IsEqual(text.NodeType, XmlNodeType.Text);
                    Validate.IsEqual(comment.NodeType, XmlNodeType.Comment);
                    Validate.IsEqual(processingInstruction.NodeType, XmlNodeType.ProcessingInstruction);
                }
 private static string CollectText(XText n)
 {
     string str = n.Value;
     if (n.parent != null)
     {
         while (n != n.parent.content)
         {
             n = n.next as XText;
             if (n == null)
             {
                 return str;
             }
             str = str + n.Value;
         }
     }
     return str;
 }
Пример #17
0
        private void CreateControlFlowSection( XElement script )
        {
            //TODO: Test this method

            var parentSection = script.XPathSelectElement( "./ancestor::text:section", Manager );
            // TODO: If ParentSection is null, throw specific exception

            var scriptValue = script.Value.Replace( "U+10FFFD", "@" );

            var beforeNode = new XText( scriptValue + "{" );

            var afterNode = new XText( "}" );

            parentSection.AddBeforeSelf( beforeNode );

            parentSection.AddAfterSelf( afterNode );

            script.Remove();
        }
Пример #18
0
    public void Parent()
    {
      JArray v = new JArray(new JConstructor("TestConstructor"), new JValue(new DateTime(2000, 12, 20)));

      Assert.AreEqual(null, v.Parent);

      JObject o =
        new JObject(
          new JProperty("Test1", v),
          new JProperty("Test2", "Test2Value"),
          new JProperty("Test3", "Test3Value"),
          new JProperty("Test4", null)
        );

      Assert.AreEqual(o.Property("Test1"), v.Parent);

      JProperty p = new JProperty("NewProperty", v);

      // existing value should still have same parent
      Assert.AreEqual(o.Property("Test1"), v.Parent);

      // new value should be cloned
      Assert.AreNotEqual(p.Value, v);

      Assert.AreEqual((DateTime)((JValue)p.Value[1]).Value, (DateTime)((JValue)v[1]).Value);

      Assert.AreEqual(v, o["Test1"]);

      XText t = new XText("XText");
      Assert.AreEqual(null, t.Parent);

      Assert.AreEqual(null, o.Parent);
      JProperty o1 = new JProperty("O1", o);
      Assert.AreEqual(o, o1.Value);

      Assert.AreNotEqual(null, o.Parent);
      JProperty o2 = new JProperty("O2", o);

      Assert.AreNotEqual(o1.Value, o2.Value);
      Assert.AreEqual(o1.Value.Children().Count(), o2.Value.Children().Count());
      Assert.AreEqual(false, JToken.DeepEquals(o1, o2));
      Assert.AreEqual(true, JToken.DeepEquals(o1.Value, o2.Value));
    }
Пример #19
0
 public void ExecuteXDocumentVariation(XNode toReplace)
 {
     XNode newValue = new XText(" ");
     XDocument xDoc = new XDocument(toReplace);
     XDocument xDocOriginal = new XDocument(xDoc);
     using (UndoManager undo = new UndoManager(xDoc))
     {
         undo.Group();
         using (EventsHelper docHelper = new EventsHelper(xDoc))
         {
             xDoc.ReplaceNodes(newValue);
             Assert.True(xDoc.Nodes().Count() == 1, "Not all content were removed");
             Assert.True(Object.ReferenceEquals(xDoc.FirstNode, newValue), "Did not replace correctly");
             docHelper.Verify(new XObjectChange[] { XObjectChange.Remove, XObjectChange.Add }, new XObject[] { toReplace, newValue });
         }
         undo.Undo();
         Assert.True(XNode.DeepEquals(xDoc, xDocOriginal), "Undo did not work!");
     }
 }
Пример #20
0
 IEnumerable<XElement> CreateRuns(XText node,bool preservespace)
 {
     var rtn = new List<XElement>();
     if(!preservespace)
     {
         var run = CreateRun(GetInnerText(node.Value, false));
         rtn.Add(run);
         return rtn;
     }
     var lines = node.Value.Split(new char[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries);
     foreach(var line in lines)
     {
         var run = CreateRun(line);
         rtn.Add(run);
         rtn.Add(CreateLineBreak());
     }
     if (rtn.Count > 0)
         rtn.Remove(rtn.Last());
     return rtn;
 } 
        private void handle_blog_archive_page(System.Net.HttpListenerContext context)
        {
            this.WriteLogMethodName();

            var xdoc = CreateHtmlDom();
            var el_body = xdoc.Element("html").Element("body");
            el_body.AddH1Element(this.BlogTitle);

            el_body.AddAnchorElement("/", "Home");
            foreach (var post in this.PostList)
            {
                var el_para = el_body.AddParagraphElement();
                var el_text =
                    new System.Xml.Linq.XText(post.DateCreated == null
                        ? "No Publish Date"
                        : post.DateCreated.Value.ToShortDateString());
                el_para.Add(el_text);

                el_para.AddAnchorElement(post.Link, post.Title);
            }
            WriteResponseString(context, xdoc.ToString(), 200, ContentType_TextHtml);
        }
        private void handle_blog_archive_page(System.Net.HttpListenerContext context)
        {
            this.WriteLogMethodName();

            var xdoc    = CreateHtmlDom();
            var el_body = xdoc.Element("html").Element("body");

            el_body.AddH1Element(this.BlogTitle);

            el_body.AddAnchorElement("/", "Home");
            foreach (var post in this.PostList)
            {
                var el_para = el_body.AddParagraphElement();
                var el_text =
                    new System.Xml.Linq.XText(post.DateCreated == null
                        ? "No Publish Date"
                        : post.DateCreated.Value.ToShortDateString());
                el_para.Add(el_text);

                el_para.AddAnchorElement(post.Link, post.Title);
            }
            WriteResponseString(context, xdoc.ToString(), 200, ContentType_TextHtml);
        }
Пример #23
0
        private void RenderMessageHint(string value)
        {
            value = new System.Xml.Linq.XText(value).ToString();
            foreach (var line in value.Split(new [] { '\n' }, StringSplitOptions.None))
            {
                PushIndent("\t");


        #line default
        #line hidden

        #line 37 "C:\Code\Personal\netfx\Extensions\System\StringResources\Source\CsTypedResx.tt"
                this.Write("/// ");


        #line default
        #line hidden

        #line 38 "C:\Code\Personal\netfx\Extensions\System\StringResources\Source\CsTypedResx.tt"
                this.Write(this.ToStringHelper.ToStringWithCulture(line));


        #line default
        #line hidden

        #line 38 "C:\Code\Personal\netfx\Extensions\System\StringResources\Source\CsTypedResx.tt"
                this.Write("\r\n");


        #line default
        #line hidden

        #line 39 "C:\Code\Personal\netfx\Extensions\System\StringResources\Source\CsTypedResx.tt"

                PopIndent();
            }
        }
Пример #24
0
private void RenderMessageHint(string value)
{
	value = new System.Xml.Linq.XText(value).ToString();
	foreach (var line in value.Split(new [] { '\n' }, StringSplitOptions.None))
    {
	    PushIndent("\t");

        
        #line default
        #line hidden
        
        #line 37 "C:\Code\Personal\netfx\Extensions\System\StringResources\Source\CsTypedResx.tt"
this.Write("/// ");

        
        #line default
        #line hidden
        
        #line 38 "C:\Code\Personal\netfx\Extensions\System\StringResources\Source\CsTypedResx.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(line));

        
        #line default
        #line hidden
        
        #line 38 "C:\Code\Personal\netfx\Extensions\System\StringResources\Source\CsTypedResx.tt"
this.Write("\r\n");

        
        #line default
        #line hidden
        
        #line 39 "C:\Code\Personal\netfx\Extensions\System\StringResources\Source\CsTypedResx.tt"

        PopIndent();
    }
}
Пример #25
0
 public void XTextChangeValue()
 {
     XText toChange = new XText("Original Value");
     String newValue = "New Value";
     XElement xElem = new XElement("root", toChange);
     XElement xElemOriginal = new XElement(xElem);
     using (UndoManager undo = new UndoManager(xElem))
     {
         undo.Group();
         using (EventsHelper eHelper = new EventsHelper(xElem))
         {
             using (EventsHelper textHelper = new EventsHelper(toChange))
             {
                 toChange.Value = newValue;
                 Assert.True(toChange.Value.Equals(newValue), "Value did not change");
                 xElem.Verify();
                 textHelper.Verify(XObjectChange.Value, toChange);
             }
             eHelper.Verify(XObjectChange.Value, toChange);
         }
         undo.Undo();
         Assert.True(XNode.DeepEquals(xElem, xElemOriginal), "Undo did not work!");
     }
 }
Пример #26
0
 public XRaw(XText text) : base(text) { }
Пример #27
0
        internal void ReadContentFrom(XmlReader r, LoadOptions o)
        {
            if ((o & (LoadOptions.SetBaseUri | LoadOptions.SetLineInfo)) == 0)
            {
                ReadContentFrom(r);
                return;
            }
            if (r.ReadState != ReadState.Interactive)
            {
                throw new InvalidOperationException(SR.InvalidOperation_ExpectedInteractive);
            }
            XContainer     c       = this;
            XNode          n       = null;
            NamespaceCache eCache  = new NamespaceCache();
            NamespaceCache aCache  = new NamespaceCache();
            string         baseUri = (o & LoadOptions.SetBaseUri) != 0 ? r.BaseURI : null;
            IXmlLineInfo   li      = (o & LoadOptions.SetLineInfo) != 0 ? r as IXmlLineInfo : null;

            do
            {
                string uri = r.BaseURI;
                switch (r.NodeType)
                {
                case XmlNodeType.Element:
                {
                    XElement e = new XElement(eCache.Get(r.NamespaceURI).GetName(r.LocalName));
                    if (baseUri != null && baseUri != uri)
                    {
                        e.SetBaseUri(uri);
                    }
                    if (li != null && li.HasLineInfo())
                    {
                        e.SetLineInfo(li.LineNumber, li.LinePosition);
                    }
                    if (r.MoveToFirstAttribute())
                    {
                        do
                        {
                            XAttribute a = new XAttribute(aCache.Get(r.Prefix.Length == 0 ? string.Empty : r.NamespaceURI).GetName(r.LocalName), r.Value);
                            if (li != null && li.HasLineInfo())
                            {
                                a.SetLineInfo(li.LineNumber, li.LinePosition);
                            }
                            e.AppendAttributeSkipNotify(a);
                        } while (r.MoveToNextAttribute());
                        r.MoveToElement();
                    }
                    c.AddNodeSkipNotify(e);
                    if (!r.IsEmptyElement)
                    {
                        c = e;
                        if (baseUri != null)
                        {
                            baseUri = uri;
                        }
                    }
                    break;
                }

                case XmlNodeType.EndElement:
                {
                    if (c.content == null)
                    {
                        c.content = string.Empty;
                    }
                    // Store the line info of the end element tag.
                    // Note that since we've got EndElement the current container must be an XElement
                    XElement e = c as XElement;
                    Debug.Assert(e != null, "EndElement received but the current container is not an element.");
                    if (e != null && li != null && li.HasLineInfo())
                    {
                        e.SetEndElementLineInfo(li.LineNumber, li.LinePosition);
                    }
                    if (c == this)
                    {
                        return;
                    }
                    if (baseUri != null && c.HasBaseUri)
                    {
                        baseUri = c.parent.BaseUri;
                    }
                    c = c.parent;
                    break;
                }

                case XmlNodeType.Text:
                case XmlNodeType.SignificantWhitespace:
                case XmlNodeType.Whitespace:
                    if ((baseUri != null && baseUri != uri) ||
                        (li != null && li.HasLineInfo()))
                    {
                        n = new XText(r.Value);
                    }
                    else
                    {
                        c.AddStringSkipNotify(r.Value);
                    }
                    break;

                case XmlNodeType.CDATA:
                    n = new XCData(r.Value);
                    break;

                case XmlNodeType.Comment:
                    n = new XComment(r.Value);
                    break;

                case XmlNodeType.ProcessingInstruction:
                    n = new XProcessingInstruction(r.Name, r.Value);
                    break;

                case XmlNodeType.DocumentType:
                    n = new XDocumentType(r.LocalName, r.GetAttribute("PUBLIC"), r.GetAttribute("SYSTEM"), r.Value);
                    break;

                case XmlNodeType.EntityReference:
                    if (!r.CanResolveEntity)
                    {
                        throw new InvalidOperationException(SR.InvalidOperation_UnresolvedEntityReference);
                    }
                    r.ResolveEntity();
                    break;

                case XmlNodeType.EndEntity:
                    break;

                default:
                    throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedNodeType, r.NodeType));
                }
                if (n != null)
                {
                    if (baseUri != null && baseUri != uri)
                    {
                        n.SetBaseUri(uri);
                    }
                    if (li != null && li.HasLineInfo())
                    {
                        n.SetLineInfo(li.LineNumber, li.LinePosition);
                    }
                    c.AddNodeSkipNotify(n);
                    n = null;
                }
            } while (r.Read());
        }
Пример #28
0
 /// <summary>
 /// Invoked for each <see cref="XText"/>
 /// </summary>
 /// <param name="text"></param>
 public virtual void Visit(XText text)
 {
     Contract.Requires<ArgumentNullException>(text != null);
 }
Пример #29
0
 public XText(XText other)
 {
     value = other.value;
 }
Пример #30
0
        internal static XNode GetXNodeFromJSNode(object node)
        {
            XNode result = null;

            if (Interop.IsRunningInTheSimulator)
            {
                // In the Simulator, we get the CSharp object associated to a DOM element by searching for the DOM element ID in the "INTERNAL_idsToUIElements" dictionary.

                object jsId = Interop.ExecuteJavaScript("$0.nodeId", node);
                if (!IsNullOrUndefined(jsId))
                {
                    string id = Convert.ToString(jsId);
                    if (XDocument.INTERNAL_idsToXNodes.ContainsKey(id))
                    {
                        result = XDocument.INTERNAL_idsToXNodes[id];
                    } //else throw an exception ?
                }
                else
                {
                    // generate a new id for the node
                    // get the type of the node (probably through node.nodeType, see the comment at the beginning of the XContainer class).
                    // create the node
                    // add the whole thing to the dictionary
                    // result = nodeCreated

                    string newId    = Guid.NewGuid().ToString();
                    int    nodeType = Convert.ToInt32(Interop.ExecuteJavaScript("$0.nodeType", node));
                    //nodeType = : 1 is XElement, 3 is XText, 8 is XComment, 9 is XDocument but is useless I think


                    switch (nodeType)
                    {
                    case 1:     //XElement
                        result = new XElement(node);
                        break;

                    case 3:     //Xtext
                        result = new XText(node);
                        result.INTERNAL_jsnode = node;
                        break;

                    case 8:     //XComment
                        break;

                    case 9:     //XDocument
                        break;

                    default:
                        break;
                    }
                    XDocument.INTERNAL_idsToXNodes.Add(newId, result);
                    Interop.ExecuteJavaScript("$0.nodeId = $1", node, newId);
                }
            }
            else
            {
                // In JavaScript, we get the CSharp object associated to a DOM element by reading the "associatedUIElement" property:

                object associatedXNode = Interop.ExecuteJavaScript("$0.associatedXNode", node);
                if (!IsNullOrUndefined(associatedXNode))
                {
                    result = (XNode)associatedXNode;
                }
                else
                {
                    // get the type of the node (probably through node.nodeType, see the comment at the beginning of the XContainer class).
                    // create the Xnode
                    // set the XNode to node.associatedXNode
                    //result = nodeCreated

                    int nodeType = Convert.ToInt32(Interop.ExecuteJavaScript("$0.nodeType", node));
                    //nodeType = : 1 is XElement, 3 is XText, 8 is XComment, 9 is XDocument but is useless I think


                    switch (nodeType)
                    {
                    case 1:     //XElement
                        result = new XElement(node);
                        break;

                    case 3:     //Xtext
                        result = new XText(node);
                        result.INTERNAL_jsnode = node;
                        break;

                    case 8:     //XComment
                        break;

                    case 9:     //XDocument
                        break;

                    default:
                        break;
                    }
                    Interop.ExecuteJavaScript("$0.nodeId = $1", node, result);
                }
            }
            return(result);
        }
Пример #31
0
            public bool ReadContentFrom(XContainer rootContainer, XmlReader r, LoadOptions o)
            {
                XNode  newNode = null;
                string baseUri = r.BaseURI;

                switch (r.NodeType)
                {
                case XmlNodeType.Element:
                {
                    XElement e = new XElement(_eCache.Get(r.NamespaceURI).GetName(r.LocalName));
                    if (_baseUri != null && _baseUri != baseUri)
                    {
                        e.SetBaseUri(baseUri);
                    }
                    if (_lineInfo != null && _lineInfo.HasLineInfo())
                    {
                        e.SetLineInfo(_lineInfo.LineNumber, _lineInfo.LinePosition);
                    }
                    if (r.MoveToFirstAttribute())
                    {
                        do
                        {
                            XAttribute a = new XAttribute(_aCache.Get(r.Prefix.Length == 0 ? string.Empty : r.NamespaceURI).GetName(r.LocalName), r.Value);
                            if (_lineInfo != null && _lineInfo.HasLineInfo())
                            {
                                a.SetLineInfo(_lineInfo.LineNumber, _lineInfo.LinePosition);
                            }
                            e.AppendAttributeSkipNotify(a);
                        } while (r.MoveToNextAttribute());
                        r.MoveToElement();
                    }
                    _currentContainer.AddNodeSkipNotify(e);
                    if (!r.IsEmptyElement)
                    {
                        _currentContainer = e;
                        if (_baseUri != null)
                        {
                            _baseUri = baseUri;
                        }
                    }
                    break;
                }

                case XmlNodeType.EndElement:
                {
                    if (_currentContainer.content == null)
                    {
                        _currentContainer.content = string.Empty;
                    }
                    // Store the line info of the end element tag.
                    // Note that since we've got EndElement the current container must be an XElement
                    XElement e = _currentContainer as XElement;
                    Debug.Assert(e != null, "EndElement received but the current container is not an element.");
                    if (e != null && _lineInfo != null && _lineInfo.HasLineInfo())
                    {
                        e.SetEndElementLineInfo(_lineInfo.LineNumber, _lineInfo.LinePosition);
                    }
                    if (_currentContainer == rootContainer)
                    {
                        return(false);
                    }
                    if (_baseUri != null && _currentContainer.HasBaseUri)
                    {
                        _baseUri = _currentContainer.parent.BaseUri;
                    }
                    _currentContainer = _currentContainer.parent;
                    break;
                }

                case XmlNodeType.Text:
                case XmlNodeType.SignificantWhitespace:
                case XmlNodeType.Whitespace:
                    if ((_baseUri != null && _baseUri != baseUri) ||
                        (_lineInfo != null && _lineInfo.HasLineInfo()))
                    {
                        newNode = new XText(r.Value);
                    }
                    else
                    {
                        _currentContainer.AddStringSkipNotify(r.Value);
                    }
                    break;

                case XmlNodeType.CDATA:
                    newNode = new XCData(r.Value);
                    break;

                case XmlNodeType.Comment:
                    newNode = new XComment(r.Value);
                    break;

                case XmlNodeType.ProcessingInstruction:
                    newNode = new XProcessingInstruction(r.Name, r.Value);
                    break;

                case XmlNodeType.DocumentType:
                    newNode = new XDocumentType(r.LocalName, r.GetAttribute("PUBLIC"), r.GetAttribute("SYSTEM"), r.Value);
                    break;

                case XmlNodeType.EntityReference:
                    if (!r.CanResolveEntity)
                    {
                        throw new InvalidOperationException(SR.InvalidOperation_UnresolvedEntityReference);
                    }
                    r.ResolveEntity();
                    break;

                case XmlNodeType.EndEntity:
                    break;

                default:
                    throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedNodeType, r.NodeType));
                }

                if (newNode != null)
                {
                    if (_baseUri != null && _baseUri != baseUri)
                    {
                        newNode.SetBaseUri(baseUri);
                    }

                    if (_lineInfo != null && _lineInfo.HasLineInfo())
                    {
                        newNode.SetLineInfo(_lineInfo.LineNumber, _lineInfo.LinePosition);
                    }

                    _currentContainer.AddNodeSkipNotify(newNode);
                    newNode = null;
                }

                return(true);
            }
        private static void AppendTextFromTextNode(FormatterState state, XText element)
        {
            var rawText = element.Value;
            var builder = new StringBuilder(rawText.Length);

            // Normalize the whitespace.
            var pendingWhitespace = false;
            var hadAnyNonWhitespace = false;
            for (int i = 0; i < rawText.Length; i++)
            {
                if (char.IsWhiteSpace(rawText[i]))
                {
                    // Whitespace. If it occurs at the beginning of the text we don't append it
                    // at all; otherwise, we reduce it to a single space.
                    if (!state.AtBeginning || hadAnyNonWhitespace)
                    {
                        pendingWhitespace = true;
                    }
                }
                else
                {
                    // Some other character...
                    if (pendingWhitespace)
                    {
                        if (builder.Length == 0)
                        {
                            state.AppendSingleSpace();
                        }
                        else
                        {
                            builder.Append(' ');
                        }

                        pendingWhitespace = false;
                    }

                    builder.Append(rawText[i]);
                    hadAnyNonWhitespace = true;
                }
            }

            if (builder.Length > 0)
            {
                state.AppendString(builder.ToString());
            }

            if (pendingWhitespace)
            {
                state.AppendSingleSpace();
            }
        }
Пример #33
0
 public XTextWrapper(XText text)
   : base(text)
 {
 }
 private static object ConvertEntities(string text)
 {
     if (text == null)
         return null;
     if (text.Length == 0)
         return null;
     string textToUse = text;
     var spacesAtBeginning = 0;
     var spacesAtEnd = 0;
     if (text[0] == ' ' || text[text.Length - 1] == ' ')
     {
         spacesAtBeginning = textToUse.TakeWhile(c => c == ' ').Count();
         var leftOverText = textToUse.Substring(spacesAtBeginning);
         if (leftOverText.Length > 1)
             spacesAtEnd = leftOverText.Reverse().TakeWhile(c => c == ' ').Count();
         textToUse = textToUse.Substring(spacesAtBeginning, textToUse.Length - spacesAtEnd - spacesAtBeginning);
     }
     object o = textToUse.ToCharArray()
         .GroupAdjacent((char c) =>
         {
             if (c == 0xf0b7 ||
                 c == 0xf0a7 ||
                 c == 0xf076 ||
                 c == 0xf0d8 ||
                 c == 0xf0a8 ||
                 c == 0xf0fc ||
                 c == 0xf0e0 ||
                 c == 0xf0b2)
                 return "-";
             if (c >= 128)
             {
                 string entity;
                 if (EntityMap.TryGetValue(c, out entity))
                     return entity;
             }
             return "-";
         })
         .Select(g =>
         {
             if (g.Key != "-")
                 return (object)(g.Select(c => new XEntity(g.Key)));
             var xt = new XText(g.Aggregate(new StringBuilder(),
                     (s, i) => s.Append(i),
                     s => s.ToString()));
             return xt;
         });
     if (spacesAtBeginning == 0 && spacesAtEnd == 0)
         return o;
     else
     {
         var atBeginning = Enumerable.Repeat(new XEntity("nbsp"), spacesAtBeginning);
         var atEnding = Enumerable.Repeat(new XEntity("nbsp"), spacesAtEnd);
         return new object[] {
             atBeginning,
             o,
             atEnding,
         };
     }
 }
        private static string WrapInXmlComment(string prefixWithLeadingSpaces, string copyrightText, string filename, StyleCopSettings settings, string newLineText)
        {
            string encodedFilename = new XAttribute("t", filename).ToString().Substring(2).Trim('"');
            string encodedCompanyName = new XAttribute("t", settings.DocumentationRules.CompanyName).ToString().Substring(2).Trim('"');
            string encodedCopyrightText = new XText(copyrightText).ToString();

            return
                $"{prefixWithLeadingSpaces} <copyright file=\"{encodedFilename}\" company=\"{encodedCompanyName}\">" + newLineText
                + encodedCopyrightText + newLineText
                + prefixWithLeadingSpaces + " </copyright>";
        }
Пример #36
0
        internal void ReadContentFrom(XmlReader r, LoadOptions o)
        {
            if ((o & (LoadOptions.SetLineInfo | LoadOptions.SetBaseUri)) == LoadOptions.None)
            {
                this.ReadContentFrom(r);
            }
            else
            {
                if (r.ReadState != System.Xml.ReadState.Interactive)
                {
                    throw new InvalidOperationException(System.Xml.Linq.Res.GetString("InvalidOperation_ExpectedInteractive"));
                }
                XContainer     parent  = this;
                XNode          n       = null;
                NamespaceCache cache   = new NamespaceCache();
                NamespaceCache cache2  = new NamespaceCache();
                string         baseUri = ((o & LoadOptions.SetBaseUri) != LoadOptions.None) ? r.BaseURI : null;
                IXmlLineInfo   info    = ((o & LoadOptions.SetLineInfo) != LoadOptions.None) ? (r as IXmlLineInfo) : null;
                do
                {
                    string baseURI = r.BaseURI;
                    switch (r.NodeType)
                    {
                    case XmlNodeType.Element:
                    {
                        XElement element = new XElement(cache.Get(r.NamespaceURI).GetName(r.LocalName));
                        if ((baseUri != null) && (baseUri != baseURI))
                        {
                            element.SetBaseUri(baseURI);
                        }
                        if ((info != null) && info.HasLineInfo())
                        {
                            element.SetLineInfo(info.LineNumber, info.LinePosition);
                        }
                        if (r.MoveToFirstAttribute())
                        {
                            do
                            {
                                XAttribute a = new XAttribute(cache2.Get((r.Prefix.Length == 0) ? string.Empty : r.NamespaceURI).GetName(r.LocalName), r.Value);
                                if ((info != null) && info.HasLineInfo())
                                {
                                    a.SetLineInfo(info.LineNumber, info.LinePosition);
                                }
                                element.AppendAttributeSkipNotify(a);
                            }while (r.MoveToNextAttribute());
                            r.MoveToElement();
                        }
                        parent.AddNodeSkipNotify(element);
                        if (!r.IsEmptyElement)
                        {
                            parent = element;
                            if (baseUri != null)
                            {
                                baseUri = baseURI;
                            }
                        }
                        break;
                    }

                    case XmlNodeType.Text:
                    case XmlNodeType.Whitespace:
                    case XmlNodeType.SignificantWhitespace:
                        if (((baseUri == null) || (baseUri == baseURI)) && ((info == null) || !info.HasLineInfo()))
                        {
                            parent.AddStringSkipNotify(r.Value);
                        }
                        else
                        {
                            n = new XText(r.Value);
                        }
                        break;

                    case XmlNodeType.CDATA:
                        n = new XCData(r.Value);
                        break;

                    case XmlNodeType.EntityReference:
                        if (!r.CanResolveEntity)
                        {
                            throw new InvalidOperationException(System.Xml.Linq.Res.GetString("InvalidOperation_UnresolvedEntityReference"));
                        }
                        r.ResolveEntity();
                        break;

                    case XmlNodeType.ProcessingInstruction:
                        n = new XProcessingInstruction(r.Name, r.Value);
                        break;

                    case XmlNodeType.Comment:
                        n = new XComment(r.Value);
                        break;

                    case XmlNodeType.DocumentType:
                        n = new XDocumentType(r.LocalName, r.GetAttribute("PUBLIC"), r.GetAttribute("SYSTEM"), r.Value, r.DtdInfo);
                        break;

                    case XmlNodeType.EndElement:
                    {
                        if (parent.content == null)
                        {
                            parent.content = string.Empty;
                        }
                        XElement element2 = parent as XElement;
                        if (((element2 != null) && (info != null)) && info.HasLineInfo())
                        {
                            element2.SetEndElementLineInfo(info.LineNumber, info.LinePosition);
                        }
                        if (parent == this)
                        {
                            return;
                        }
                        if ((baseUri != null) && parent.HasBaseUri)
                        {
                            baseUri = parent.parent.BaseUri;
                        }
                        parent = parent.parent;
                        break;
                    }

                    case XmlNodeType.EndEntity:
                        break;

                    default:
                        throw new InvalidOperationException(System.Xml.Linq.Res.GetString("InvalidOperation_UnexpectedNodeType", new object[] { r.NodeType }));
                    }
                    if (n != null)
                    {
                        if ((baseUri != null) && (baseUri != baseURI))
                        {
                            n.SetBaseUri(baseURI);
                        }
                        if ((info != null) && info.HasLineInfo())
                        {
                            n.SetLineInfo(info.LineNumber, info.LinePosition);
                        }
                        parent.AddNodeSkipNotify(n);
                        n = null;
                    }
                }while (r.Read());
            }
        }
Пример #37
0
        private void ShowXNode(XNode xnode, TreeViewItemXNode parentNode, int position = -1)
        {
            var newItem = new TreeViewItemXNode();

              newItem.XNode = xnode;

              if (typeof(XComment).IsAssignableFrom(xnode.GetType())) {
            var comment = (XComment)xnode;

            newItem.Header = comment.Value;

              } else if (typeof(XElement).IsAssignableFrom(xnode.GetType())) {
            var element = (XElement)xnode;

            //TreeViewItem to close opening tag.
            newItem.EndingItem = new TreeViewItemXNode();
            newItem.EndingItem.XNode = element;
            newItem.EndingItem.BeginItem = newItem;
            newItem.EndingItem.Header = "</" + element.Name + ">";

            if (element.HasElements) {
              var elementsEnumerator = element.Nodes().GetEnumerator();

              while (elementsEnumerator.MoveNext()) {
            this.ShowXNode(elementsEnumerator.Current, newItem);
              }
            } else if (element.Value.Length > 0) {
              //TreeViewItem to show element value.
              //When an XElement has a value, it has an XText node, which is in the first position.
              newItem.ValueItem = new TreeViewItemXNode();
              newItem.ValueItem.BeginItem = newItem;
              newItem.ValueItem.XNode = element.FirstNode;
              newItem.ValueItem.Header = element.Value;
              newItem.Items.Add(newItem.ValueItem);
            }

            if (newItem.ValueItem == null) {
              //Create an XNode to hold the element's value.
              var text = new XText("");
              element.AddFirst(text);

              //TreeViewItem to show element value.
              newItem.ValueItem = new TreeViewItemXNode();
              newItem.ValueItem.BeginItem = newItem;
              newItem.ValueItem.XNode = text;
              newItem.ValueItem.Header = "";
            }

            this.RefreshXElementItemHeader(newItem);

              } else if (typeof(XText).IsAssignableFrom(xnode.GetType())) {
            var text = (XText)xnode;

            newItem.BeginItem = parentNode;
            newItem.Header = text.Value;
            parentNode.ValueItem = newItem;

              } else {
            newItem.Header = "UNKNOWN XNODE!!!";
              }

              if (parentNode == null)
            tvXmlDocument.Items.Add(newItem);
              else {
            if (position == -1)
              parentNode.Items.Add(newItem);
            else
              parentNode.Items.Insert(position, newItem);
              }

              if (newItem.HasItems) {
            newItem.Collapsed += new RoutedEventHandler(ItemCollapsed);
            newItem.Expanded += new RoutedEventHandler(ItemExpanded);
              }
        }
Пример #38
0
        public static void AddText(this System.Xml.Linq.XElement el, string s)
        {
            var new_text = new System.Xml.Linq.XText(s);

            el.Add(new_text);
        }
Пример #39
0
        private void GetValuesFromVariable(string name, XText xt, bool path)
        {
            string s;
            if (path)
            {
                if (xt != null)
                    //s = xt.Parent.zGetPath();
                    s = xt.zGetPath();
                else
                    s = null;
                _values.Add(new NamedValue(name + "_path", s));

                if (xt != null)
                    s = xt.Parent.Name.ToString();
                else
                    s = null;
                _values.Add(new NamedValue(name + "_node", s));

                name += "_value";
            }
            if (xt != null)
                s = xt.Value.Trim();
            else
                s = null;
            _values.Add(new NamedValue(name, s));
        }
Пример #40
0
        static void HandleCollectedXText(
            Func <string, StringBuilder, bool> actualTextProcessor,
            string startLine,
            List <XText> currentXText,
            StringBuilder currentText,
            bool removeDefaultStartLine)
        {
            bool hasActualText = false;

            Debug.Assert(currentXText.Count != 0);
            int newLineCount = 0;

            for (int i = 0; i < currentText.Length; ++i)
            {
                char car = currentText[i];
                if (car == '\n')
                {
                    ++newLineCount;
                }
                else if (car != '\r' && car != '\t' && car != ' ')
                {
                    hasActualText = true;
                    break;
                }
            }
            XText replacement = null;

            if (!hasActualText)
            {
                if (!removeDefaultStartLine)
                {
                    string newText = startLine;
                    if (newLineCount >= 2)
                    {
                        newText = Environment.NewLine + newText;
                    }
                    if (currentXText.Count != 1 || currentXText[0].Value != newText)
                    {
                        replacement = new XText(newText);
                    }
                }
            }
            else
            {
                if (actualTextProcessor?.Invoke(startLine, currentText) ?? false)
                {
                    if (currentText.Length > 0)
                    {
                        replacement = new XText(currentText.ToString());
                    }
                }
            }
            if (replacement != null)
            {
                currentXText[currentXText.Count - 1].AddAfterSelf(replacement);
                currentXText.Remove();
            }
            else if (!hasActualText && removeDefaultStartLine)
            {
                currentXText.Remove();
            }
        }