Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#帮助解析xml_C#_Xml_Parsing - Fatal编程技术网

C#帮助解析xml

C#帮助解析xml,c#,xml,parsing,C#,Xml,Parsing,大家好。我一直在尝试获取特定XML节点的属性,但失败了。我正在使用System.Xml 以下是XML代码: <report type="Full" sr="28"> ... </report> XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load("test.xml"); XmlNodeList reportNodeList = xmlDocument.GetElementsByTagNam

大家好。我一直在尝试获取特定XML节点的属性,但失败了。我正在使用System.Xml

以下是XML代码:

<report type="Full" sr="28">
    ...
</report>
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:

您只需要使用Value而不是ToString:


请阅读并解释它到底是如何“不起作用的”。请阅读并解释它到底是如何“不起作用的”。最初的问题是我没有将
对象引用设置为对象的实例。
错误。我意识到test.xml文件中不存在sr属性,这是我的错误。但是,这解决了第二个问题,ToString()给我的是类型的名称(XmlAttribute),而不是属性的值?我必须获得其他几个节点的属性,对所有节点执行相同的操作将造成巨大的混乱。另一种方法是使用xpath。。。e、 g,string reportType=xmlDocument.SelectSingleNode(“report/@type”).Value;最初的问题是,我没有将
对象引用设置为对象的实例。
错误。我意识到test.xml文件中不存在sr属性,这是我的错误。但是,这解决了第二个问题,ToString()给我的是类型的名称(XmlAttribute),而不是属性的值?我必须获得其他几个节点的属性,对所有节点执行相同的操作将造成巨大的混乱。另一种方法是使用xpath。。。e、 g,string reportType=xmlDocument.SelectSingleNode(“report/@type”).Value;
string reportType = reportNodeAttributeCollection.GetNamedItem("type").Value;
string sr = reportNodeAttributeCollection.GetNamedItem("sr").Value;