使用XmlDocument读取XML属性

时间:2009-06-01 05:49:53

标签: c# .net xml xmldocument

如何使用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 个答案:

答案 0 :(得分:103)

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

答案 1 :(得分:87)

你应该研究XPath。一旦你开始使用它,你会发现它比迭代列表更有效,更容易编码。它还可以让您直接获得所需的东西。

然后代码类似于

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

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

答案 2 :(得分:8)

如果您更喜欢该语法,则可以迁移到XDocument而不是XmlDocument,然后使用Linq。类似的东西:

var q = (from myConfig in xDoc.Elements("MyConfiguration")
         select myConfig.Attribute("SuperString").Value)
         .First();

答案 3 :(得分:6)

我有一个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

答案 4 :(得分:5)

或许

XmlDocument.Attributes? (其中有一个GetNamedItem方法可能会按照您的意愿执行,尽管我总是只迭代属性集合)

答案 5 :(得分:1)

假设您的示例文档位于字符串变量doc

> XDocument.Parse(doc).Root.Attribute("SuperNumber")
1

答案 6 :(得分: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命名空间herehere的更多信息。