我正在尝试显示xml文件中的数据。我无法获得子元素(类别和单元格)的属性。我收到System.NullReferenceException错误。如何显示子元素?
这是xml的一部分
<group number="3704542" text="3704542" varName="BATCH_NO">
<category number="1" text="1">
<dimension axis="column" text="Variables">
<category label="Batch Run" text="Batch Run" varName="BATCH_RUN_ID" variable="true">
<cell number="4202" text="4202" varName="BATCH_RUN_ID"/>
</category>
<category label="Application" text="Application" varName="APP_ID" variable="true">
<cell label="Calibration" number="101" text="Calibration" varName="APP_ID"/>
</category>
</dimension>
</category>
</group>
这是c#代码
private void GetXMLData1()
{
try
{
XNamespace ns = "http://www.ibm.com/software/analytics/spss/xml/oms";
XDocument testXML = XDocument.Load(@"C:\Users\byilmaz\Desktop\SPSS_SITE\test.xml");
var cats = from cat in testXML.Descendants(ns + "dimension").Where
(cat => (string)cat.Attribute("axis") == "column" && (string)cat.Attribute("text") == "Variables")
select new
{
groupName = cat.Parent.Parent.Attribute("number").Value,
catId = cat.Parent.Attribute("number").Value,
//catName = cat.Element("category").Attribute("label").Value,
};
foreach (var cat in cats)
{
xmlTitle.Text += "Group Name: " + cat.groupName + " and Cat Id: " + cat.catId + "</br>";
//xmlTitle.Text += "Cat Name: " + cat.catName + " </br>";
}
}
catch (Exception err)
{
throw (err);
}
}
,输出为:
当我从下面的代码中取消注释行时,我收到System.NullReferenceException错误。
//catName = cat.Element("category").Attribute("label").Value,