C# 帮助解析 xml
本文关键字:xml 帮助 | 更新日期: 2023-09-27 18:35:07
大家好。我一直在尝试获取特定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 方面有一些经验,但只有它的基础知识。有人可以帮忙吗?
提前感谢!
你只需要使用Value而不是ToString:
string reportType = reportNodeAttributeCollection.GetNamedItem("type").Value;
string sr = reportNodeAttributeCollection.GetNamedItem("sr").Value;