0

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?

4

2 回答 2

1

您可以使用 LINQ to XML 遍历所有二级元素:

  var xdoc = XDocument.Load(@"C:\test.xml");
    foreach (var element in xdoc.Element("DiagReport").Elements().Elements())
    {
        if (element.Name == "Result")
        {
            string value = element.Value;
        }
    }
于 2013-07-09T00:02:43.490 回答
0

您可以使用Linq to Xml查询您的Xml文档,您可以搜索ElementsAttributes并获取您需要的内容。

更多信息可以在这里找到:基本查询(LINQ to XML)

您可以创建如下所示的简单查询。

  XElement root = XElement.Parse(File.ReadAllText("C:\\Test.xml"));
  var test = new 
  {
      ToolVersion = root.Descendants("ToolVersion").FirstOrDefault().Value,
      Result = root.Descendants("Result").FirstOrDefault().Value
  };
于 2013-07-08T23:50:07.493 回答