简体   繁体   中英

parsing XML content - C#

I have not used XML for very long and need to extract the useful information from an XML response. If there are 2 tags that are the same but have a different name eg

    <lst name = "stack">
       <str>Ola</str>
       <lst name = "overflow">
          <str>Hello</str>
       </lst>
     </lst>

How would I extract the contents of the tag with name="overflow"?

You can use LINQ To XML:

var result = XDocument.Parse(xml)
                .Descendants("lst")
                .Where(e => (string) e.Attribute("name") == "overflow")
                .Descendants("str")
                .Select(x => x.Value)
                .FirstOrDefault();

Try this to start:

XPathDocument docNav = new XPathDocument(pathName);
XPathNavigator nav = docNav.CreateNavigator();
XmlNamespaceManager ns = new XmlNamespaceManager(nav.NameTable);

string val =  nav.SelectSingleNode(@"/lst/lst[@name='overflow']/str")

These are good resources for simple XPath navigation and .NET XML Parsing:

http://www.w3schools.com/xpath/

http://www.codeproject.com/Articles/52079/Using-XPathNavigator-in-C

You may use the System.Xml.Linq namespace:

var xDoc = XDocument.Parse(xml);
var result = xDoc.Descendants()
    .Where(d => 
        d.Name == "lst" && 
        d.Attributes("name").FirstOrDefault()!=null &&
        d.Attributes("name").FirstOrDefault().Value == "overflow")
    .FirstOrDefault();

User Linq to xml

var xmlFile = XDocument.Load(someFile);
var query = from item in xmlFile.Descendants("childobject")
            where !String.IsNullOrEmpty(item.Attribute("using")
            select new 
            {
                AttributeValue = item.Attribute("using").Value
            };

You can do it with LINQ to XML:

var doc = XDocument.Load("YourXMLPath.xml");
var content = doc
.Element("lst")
.Elements("lst")
.Where(e=>((string) e.Attribute("name") ?? "")=="overflow")
.Select(e=>e.Element("str").InnerText())
.FirstOrDefault();

LINQ to XML in System.Xml.Linq namespace.

const string xml = @"<lst name = ""stack""><str>Ola</str><lst name = ""overflow""><str>Hello</str></lst></lst>";

XDocument doc = XDocument.Parse(xml);

IEnumerable<XElement> overflow = doc.Root.Elements("lst").Where(x => (string) x.Attribute("name") == "overflow");

XElement firstOverflow = overflow.FirstOrDefault();

string value = firstOverflow.Descendants("str").FirstOrDefault(x => x.Value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM