83

如何使用 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> 

我将如何读取 XML 属性 SuperNumber 和 SuperString?

目前我正在使用 XmlDocument,并且我得到了使用 XmlDocument 之间的值,GetElementsByTagName()并且效果非常好。我只是不知道如何获得属性?

4

7 回答 7

119
XmlNodeList elemList = doc.GetElementsByTagName(...);
for (int i = 0; i < elemList.Count; i++)
{
    string attrVal = elemList[i].Attributes["SuperString"].Value;
}
于 2009-06-01T05:58:10.770 回答
89

您应该查看XPath。一旦你开始使用它,你会发现它比遍历列表更高效、更容易编写代码。它还可以让你直接得到你想要的东西。

然后代码将类似于

string attrVal = doc.SelectSingleNode("/MyConfiguration/@SuperNumber").Value;

请注意,XPath 3.0 于 2014 年 4 月 8 日成为 W3C 推荐标准。

于 2009-06-01T06:07:14.497 回答
8

您可以迁移到 XDocument 而不是 XmlDocument,然后如果您更喜欢该语法,请使用 Linq。就像是:

var q = (from myConfig in xDoc.Elements("MyConfiguration")
         select myConfig.Attribute("SuperString").Value)
         .First();
于 2009-06-01T07:23:33.887 回答
8

我有一个 XML 文件 books.xml

<ParameterDBConfig>
    <ID Definition="1" />
</ParameterDBConfig>

程序:

XmlDocument doc = new XmlDocument();
doc.Load("D:/siva/books.xml");
XmlNodeList elemList = doc.GetElementsByTagName("ID");     
for (int i = 0; i < elemList.Count; i++)     
{
    string attrVal = elemList[i].Attributes["Definition"].Value;
}

现在,attrVal具有 的值ID

于 2012-06-05T10:50:39.080 回答
5

XmlDocument.Attributes也许?(它有一个方法 GetNamedItem 可能会做你想要的,虽然我一直只是迭代属性集合)

于 2009-06-01T05:53:48.967 回答
1

假设您的示例文档在字符串变量中doc

> XDocument.Parse(doc).Root.Attribute("SuperNumber")
1
于 2013-03-17T19:55:43.643 回答
1

如果您的 XML 包含命名空间,那么您可以执行以下操作来获取属性的值:

var xmlDoc = new XmlDocument();

// content is your XML as string
xmlDoc.LoadXml(content);

XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());

// make sure the namespace identifier, URN in this case, matches what you have in your XML 
nsmgr.AddNamespace("ns", "urn:oasis:names:tc:SAML:2.0:protocol");

// get the value of Destination attribute from within the Response node with a prefix who's identifier is "urn:oasis:names:tc:SAML:2.0:protocol" using XPath
var str = xmlDoc.SelectSingleNode("/ns:Response/@Destination", nsmgr);
if (str != null)
{
    Console.WriteLine(str.Value);
}

有关 XML 名称空间的更多信息,请点击此处此处

于 2016-03-01T19:47:02.297 回答