[英]How to get specific attributes from all xml files in directory?
I have a folder full of xml files. 我有一个充满xml文件的文件夹。 In these files many of them share a common attribute (Name), but have a secondary attribute that is different.
在这些文件中,许多文件共享一个公共属性(名称),但具有一个不同的辅助属性。 I want to get a list of the unique entries based off reading these xml files.
我想通过阅读这些xml文件来获得唯一条目的列表。 Below is an example of what the various xml files will contain.
以下是各种xml文件将包含的内容的示例。
File 1 文件1
<?xml version="1.0" encoding="UTF-8"?>
<results date="2013-12-29">
<A uniqueId="1234" Name="My-Machine"/>
<error number="555">
<description><![CDATA[House on Fire]]></description>
</error>
</results>
File 2 文件2
<?xml version="1.0" encoding="UTF-8"?>
<results date="2013-12-29">
<A uniqueId="1234" Name="My-Machine"/>
<error number="556">
<description><![CDATA[House in flood]]></description>
</error>
</results>
File 3 文件3
<?xml version="1.0" encoding="UTF-8"?>
<results date="2013-12-29">
<A uniqueId="1234" Name="My-Machine"/>
<error number="556">
<description><![CDATA[House in flood]]></description>
</error>
</results>
I need to be able to read all the files, add each Name and description to a list (or possibly array). 我需要能够读取所有文件,将每个名称和描述添加到列表(或可能是数组)中。 Output from example would look like this:
示例的输出如下所示:
Name="MyMachine", description="![CDATA[House is flooding]]";
Name="MyMachine", description="![CDATA[House on fire]]";
Name="MyMachine", description="![CDATA[House on fire]]";
It seems LINQ may be the best way to handle this since the files are very small in content. 似乎LINQ可能是处理此问题的最佳方法,因为文件内容很小。
Here is a way to read that description
element content from one file: 这是一种从一个文件读取
description
元素内容的方法:
var xDoc = XDocument.Load("Input.xml");
var name = "My-Machine";
var aElement = xDoc.Root.Element("A");
string description = null;
if ((string)aElement.Attribute("Name") == name)
description = (string)xDoc.Root.Element("error").Element("description");
It will return the element value when Name
attribute value matches your name
variable. 当
Name
属性值与您的name
变量匹配时,它将返回元素值。 Otherwise description
will be null
. 否则
description
将为null
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.