Query Collection of all XML Elements

北慕城南 提交于 2019-12-24 20:01:51

问题


I'm looking to parse an XML file, and have the ability to search any element.

My XML code looks rather nontraditional (out of my control):

<DiagReport>
<LicensingData>
  <ToolVersion>6.3.9431.0</ToolVersion>
  <LicensingStatus>SL_LICENSING</LicensingStatus>
</LicensingData>
<Health>
  <Result>PASS</Result>
  <TamperedItems></TamperedItems>
</Health>
<Genuine>
  <ServerProps>GenuineId</ServerProps>
</Genuine>
</DiagReport>

I'd like to load each singular element into a collection, i.e. one collection including ToolVersion, Result, etc. From there, I'd like to iterate through each element/name pair, and depending upon the element, do something different:

if (element.Equals(Result))
    //do something with "PASS"

Is this possible to do with LINQ?


回答1:


You can use LINQ to XML to iterate through all second level elements:

  var xdoc = XDocument.Load(@"C:\test.xml");
    foreach (var element in xdoc.Element("DiagReport").Elements().Elements())
    {
        if (element.Name == "Result")
        {
            string value = element.Value;
        }
    }



回答2:


You can use Linq to Xml to query your Xml document, you can search Elements, Attributes and grab what you need.

More information can be found here: Basic Queries (LINQ to XML)

And you can creat simple querys like below.

  XElement root = XElement.Parse(File.ReadAllText("C:\\Test.xml"));
  var test = new 
  {
      ToolVersion = root.Descendants("ToolVersion").FirstOrDefault().Value,
      Result = root.Descendants("Result").FirstOrDefault().Value
  };


来源:https://stackoverflow.com/questions/17537604/query-collection-of-all-xml-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!