C # Xml Analysis from StringBuilder

I have a StringBuilder with the contents of an XML file. Inside the XML file is the root tag <root>and contains several tags <node>.

I would like to parse XML to read tag values ​​inside s, but not sure how to do this.

Should I use some C # XML data type for this?

Thanks in advance

+3
source share
7 answers
StringBuilder sb = new StringBuilder (xml);

TextReader textReader = new StringReader (sb.ToString ());
XDocument xmlDocument = XDocument.Load (textReader);

var nodeValueList = from node in xmlDocument.Descendants ("node")
                    select node.Value;
+6
source

You must use the classes available in System.Xmlor System.Xml.Linqfor XML parsing.

XDocument LINQ XML , . , XmlDocument ( .NET 3.5).

XDocument StringBuilder :

var doc = XDocument.Parse( stringBuilder.ToString() );

FirstNode, Descendents() , XML. XDocument LINQ, , :

var someData = from node in doc.Descendants ("yourNodeType")
               select node.Value; // etc..
+2

, , XmlReader.

using(var sr = new StringReader(stringBuilder.ToString)) {
  using(var xr = XmlReader.Create(sr)) {
    while(xr.Read()) {
      if(xr.IsStartElement() && xr.LocalName == "node")
        xr.ReadElementString(); //Do something here
    }
  }
}
+1

XDocument.Parse(...)

0

, XmlDocument . , , :

var doc=new XmlDocument();
doc.LoadXml(stringBuilder.TosTring());
XmlNodeList elemList = doc.GetElementsByTagName("node");
for (int i=0; i < elemList.Count; i++)
{   
  XmlNode node=elemList[i];
  Console.WriteLine(node.InnerText);
}  

Node, .

0

XML. System.Xml , XmlDocument, XmlReader XmlWriter. # 3.0, System.Xml.Linq XDocument.

0

XML, XML #.

XML obj #

0
source

Source: https://habr.com/ru/post/1766417/


All Articles