使用XmlDocument读取XML属性

84

如何使用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()获取之间的值非常好用。但我无法弄清楚如何获取属性?

7个回答

121
XmlNodeList elemList = doc.GetElementsByTagName(...);
for (int i = 0; i < elemList.Count; i++)
{
    string attrVal = elemList[i].Attributes["SuperString"].Value;
}

非常感谢。它真的有效,而且不需要任何路径和其他东西。简直太棒了! - Nani

91

你应该了解XPath。一旦开始使用,你会发现它比遍历列表更高效、编码更容易。它还可以直接获取你想要的内容。

然后代码将类似于

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

注意,XPath 3.0于2014年4月8日成为W3C建议。

8
你可以迁移到XDocument而不是XmlDocument,然后使用Linq语法。像这样:
你可以迁移到XDocument而不是XmlDocument,然后使用Linq语法。像这样:
var q = (from myConfig in xDoc.Elements("MyConfiguration")
         select myConfig.Attribute("SuperString").Value)
         .First();

8

我有一个名为books.xml的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

5
也许是 XmlDocument.Attributes?(该方法有一个名为 GetNamedItem 的方法,可能会做你想要的事情,尽管我总是遍历属性集合)

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命名空间的更多信息在这里在这里


1
假设您的示例文档存储在字符串变量doc中。
> XDocument.Parse(doc).Root.Attribute("SuperNumber")
1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接