tags:

views:

102

answers:

5

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

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

A: 

You can parse xml with XmlDocument class or XElement class

Andrew
Or to a dynamic (since .NET 4)
Ivo
+2  A: 

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
       };
Steve Hook
+1  A: 

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")
            };
Anthony Pegram
A: 

The overall appearance of the XML: ?return? ?item? ?attr1?1?/attr1? ?attr2?X?/attr2? ?/item? ?item? ?attr1?2?/attr1? ?attr2?Y?/attr2? ?/item? ... ?/return?

where ? -> < or >

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

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

    }
}
fishhead