Get xml attribute values as string[]

 ̄綄美尐妖づ 提交于 2019-12-22 18:48:10

问题


My xml file has something like this:
...
<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[]. Maybe a foreach loop?


I followed codemeit's and I keep getting an error:Data at the root level is invalid. Line 1, position 1. My xml file is
<KeyWords>
...
<KeyWord name = "if" />
...
</KeyWord>


New problem The '\' character, hexadecimal value 0x5C, cannot be included in a name. but the same file.


回答1:


Assume let variable testXml is equal to the follow xml string

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

Use XElement and LINQ to extract the name attribute values

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"}

UPDATE

Thanks to @SLaks comment, we could actually just do

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



回答2:


You can make use of XmlNodeList class. You need to pass proper XPATH to fetch the values and iterate through the list.



来源:https://stackoverflow.com/questions/2035991/get-xml-attribute-values-as-string

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