使用 XmlDocument 读取 XML 属性
如何使用 C# 的 XmlDocument 读取 XML 属性?
我有一个 XML 文件,看起来有点像这样:
<?xml version="1.0" encoding="utf-8" ?>
<MyConfiguration xmlns="http://tempuri.org/myOwnSchema.xsd" SuperNumber="1" SuperString="whipcream">
<Other stuff />
</MyConfiguration>
How will I read the XML attribute SuperNumber and SuperString?
目前我正在使用 XmlDocument,并且使用 XmlDocument 的 GetElementsByTagName()
获取中间的值,效果非常好。 我只是不知道如何获得属性?
How can I read an XML attribute using C#'s XmlDocument?
I have an XML file which looks somewhat like this:
<?xml version="1.0" encoding="utf-8" ?>
<MyConfiguration xmlns="http://tempuri.org/myOwnSchema.xsd" SuperNumber="1" SuperString="whipcream">
<Other stuff />
</MyConfiguration>
How would I read the XML attributes SuperNumber and SuperString?
Currently I'm using XmlDocument, and I get the values in between using XmlDocument's GetElementsByTagName()
and that works really well. I just can't figure out how to get the attributes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
如果您的 XML 包含命名空间,则可以执行以下操作以获得属性的值:
有关 XML 命名空间的更多信息 此处和此处。
If your XML contains namespaces, then you can do the following in order to obtain the value of an attribute:
More on XML namespaces here and here.
假设您的示例文档位于字符串变量
doc
中Assuming your example document is in the string variable
doc
XmlDocument.Attributes
也许? (其中有一个方法 GetNamedItem 可能会做你想要的事情,尽管我总是只是迭代属性集合)XmlDocument.Attributes
perhaps? (Which has a method GetNamedItem that will presumably do what you want, although I've always just iterated the attribute collection)我有一个 Xml 文件 books.xml
程序:
现在,
attrVal
的值为ID
。I have an Xml File books.xml
Program:
Now,
attrVal
has the value ofID
.您可以迁移到 XDocument 而不是 XmlDocument,然后使用 Linq(如果您喜欢该语法)。 就像是:
You can migrate to XDocument instead of XmlDocument and then use Linq if you prefer that syntax. Something like:
您应该查看 XPath。 一旦开始使用它,您会发现它比迭代列表更高效且更容易编码。 它还可以让您直接获得您想要的东西。
那么代码将类似于“
请注意,XPath 3.0 已于 2014 年 4 月 8 日成为 W3C 推荐标准”。
You should look into XPath. Once you start using it, you'll find its a lot more efficient and easier to code than iterating through lists. It also lets you directly get the things you want.
Then the code would be something similar to
Note that XPath 3.0 became a W3C Recommendation on April 8, 2014.