大家好日子。我一直试图获取特定XML节点的属性,但我失败了。我正在使用 System.Xml 。
以下是XML代码:
<report type="Full" sr="28">
...
</report>
我试图获取类型和 sr 属性。
以下是我尝试的内容:
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load("test.xml");
XmlNodeList reportNodeList = xmlDocument.GetElementsByTagName("report");
XmlAttributeCollection reportNodeAttributeCollection = reportNodeList.Item(0).Attributes;
string reportType = reportNodeAttributeCollection.GetNamedItem("type").ToString(); //Object reference not set to an instance of an object.
string sr = reportNodeAttributeCollection.GetNamedItem("sr").ToString();
我没想到它会起作用,但事实并非如此。我有一些解析XML的经验,但只有它的基础知识。有人可以帮忙吗?
提前致谢!
答案 0 :(得分:3)
你只需要使用 Value 而不是 ToString :
string reportType = reportNodeAttributeCollection.GetNamedItem("type").Value;
string sr = reportNodeAttributeCollection.GetNamedItem("sr").Value;