parsing XML content - C#

前端 未结 6 1472
轮回少年
轮回少年 2021-01-21 00:40

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



        
相关标签:
6条回答
  • 2021-01-21 00:57

    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();
    
    0 讨论(0)
  • 2021-01-21 01:03

    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
                };
    
    0 讨论(0)
  • 2021-01-21 01:07

    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);
    
    0 讨论(0)
  • 2021-01-21 01:09

    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

    0 讨论(0)
  • 2021-01-21 01:10

    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();
    
    0 讨论(0)
  • 2021-01-21 01:22

    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();
    
    0 讨论(0)
提交回复
热议问题