简体   繁体   English

以字符串形式获取xml属性值[]

[英]Get xml attribute values as string[]

My xml file has something like this: 我的xml文件具有以下内容:
...
<Keyword name = "if" />
<Keyword name = "else" />
<Keyword name = "is" />
...

So how can I recursively get all of the values of the name attribute and add them to a List<string> or string[] . 因此,如何递归获取name属性的所有值并将它们添加到List<string>string[] Maybe a foreach loop? 也许是一个foreach循环?


I followed codemeit's and I keep getting an error: Data at the root level is invalid. Line 1, position 1. 我遵循了codemeit的方法,但始终出现错误: Data at the root level is invalid. Line 1, position 1. Data at the root level is invalid. Line 1, position 1. My xml file is Data at the root level is invalid. Line 1, position 1.我的xml文件是
<KeyWords>
...
<KeyWord name = "if" />
...
</KeyWord>


New problem The '\\' character, hexadecimal value 0x5C, cannot be included in a name. 新问题The '\\' character, hexadecimal value 0x5C, cannot be included in a name. but the same file. 但是相同的文件。

Assume let variable testXml is equal to the follow xml string 假设让变量testXml等于跟随的xml字符串

<Keywords>
 <Keyword name = "if" />
 <Keyword name = "else" />
 <Keyword name = "is" />
</Keywords>

Use XElement and LINQ to extract the name attribute values 使用XElement和LINQ提取名称属性值

var myXml = XElement.Parse(testXml );
var myArray = myXml.Elements().Where(n => n.Name.LocalName.Equals("Keyword"))
                    .Select(n => n.Attribute("name").Value)
                    .ToArray();

myArray will contain {"if", "else", "is"} myArray将包含{“ if”,“ else”,“ is”}

UPDATE UPDATE

Thanks to @SLaks comment, we could actually just do 感谢@SLaks评论,我们实际上可以做

var myArray = myXml.Elements("Keyword").Attributes("name").Select(n => n.Value);

You can make use of XmlNodeList class. 您可以使用XmlNodeList类。 You need to pass proper XPATH to fetch the values and iterate through the list. 您需要传递适当的XPATH来获取值并遍历列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM