简体   繁体   English

C#帮助解析xml

[英]C# Help parsing xml

Good day everyone. 今天是个好日子。 I've been trying to get the attributes of a specific XML node but I'm failing. 我一直在尝试获取特定XML节点的属性,但是失败了。 I'm using System.Xml . 我正在使用System.Xml

Here's the XML code: 这是XML代码:

<report type="Full" sr="28">
    ...
</report>

I'm trying to get the type and sr attributes. 我正在尝试获取typesr属性。

Here's what I've tried: 这是我尝试过的:

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();

I didn't expect it to work and it didn't. 我没想到它会起作用,也没有。 I have some experience with parsing XML but only the very basics of it. 我有一些解析XML的经验,但是只有它的基本知识。 Could someone help? 有人可以帮忙吗?

Thanks in advance! 提前致谢!

you just need to use Value instead of ToString : 您只需要使用Value而不是ToString即可

string reportType = reportNodeAttributeCollection.GetNamedItem("type").Value;
string sr = reportNodeAttributeCollection.GetNamedItem("sr").Value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM