获取 xml 属性值作为 string[] [英] Get xml attribute values as string[]

查看:26
本文介绍了获取 xml 属性值作为 string[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 xml 文件是这样的:
<代码>...
<关键字名称 = "if"/>
<关键字名称 = "else"/>
<关键字名称 = "is"/>
...
那么如何递归获取 name 属性的所有值并将它们添加到 Liststring[] 中.也许是一个 foreach 循环?

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?

我遵循了 codemeit,但一直收到错误消息:根级别的数据无效.第 1 行,位置 1. 我的 xml 文件是
<关键字>
<代码>...

<代码>...

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>

新问题'\'字符,十六进制值0x5C,不能包含在一个名称中.但是同一个文件.

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

推荐答案

假设让变量testXml等于后面的xml字符串

Assume let variable testXml is equal to the follow xml string

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

使用 XElement 和 LINQ 提取名称属性值

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 将包含 {"if", "else", "is"}

myArray will contain {"if", "else", "is"}

更新

感谢@SLaks 的评论,我们实际上可以做到

Thanks to @SLaks comment, we could actually just do

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

这篇关于获取 xml 属性值作为 string[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆