parsing XML content - C#

2020-04-11 11:01发布

问题:

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 e.g

    <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"?

回答1:

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();


回答2:

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



回答3:

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();


回答4:

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
            };


回答5:

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();


回答6:

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);


标签: c# asp.net xml