开发者

How do I parse this simple XML in C#?

开发者 https://www.devze.com 2022-12-26 10:30 出处:网络
I want parse a SOAP xml response in C# (but I can\'t use standard SOAP interface, because wsld is incorrect).

I want parse a SOAP xml response in C# (but I can't use standard SOAP interface, because wsld is incorrect).

开发者_StackOverflow中文版

When parsing I want to have all elements with name (list element with name) and access to all its children.

The overall appearance of the XML:

<return>
  <item>
   <attr1>1</attr1>
   <attr2>X</attr2>
  </item>
  <item>
   <attr1>2</attr1>
   <attr2>Y</attr2>
  </item>
...
</return>

Regards


You could use some linq syntax to get to your xml. Start off with a new using

using System.Xml.Linq;

then you can write a linq query to open your xml file. (in my example it is a web app but you could change that) Just get the descendants of the element that is grouping the elements you want to parse. Then do something with the result. In my case I am populating a new object with the exact values I want.

XDocument changesetXML = XDocument.Load(Server.MapPath(@"~\changesets.xml"));

return from changeset in changesetXML.Descendants("Changeset")
       select new NewsTopic
       {
           DateAdded = changeset.Element("Date").Value,
           Content = changeset.Element("Summary").Value
       };


Using LINQ to XML, it's as simple as doing something like the following

XDocument document = XDocument.Load(fileName); // or .Parse(string) + other methods

var query = from item in document.Descendants("item")
            select new 
            {
               Attr1 = (int)item.Element("attr1"),
               Attr2 = (string)item.Element("attr2")
            };


You can parse xml with XmlDocument class or XElement class


XmlDocument doc = new XmlDocument();
doc.Load(“myxml.xml");

foreach(XmlNode xn in doc) 
  {
  foreach(XmlElement element in xn)
    {
  //do something

    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号