今天是我第一次接触 LINQ,所以说我是新手是轻描淡写的。所以我要做的是解析 STAT 元素的值及其属性。我的示例 XML 看起来像这样。
<ILS TGT="00-25-CE-94-00-05" PID="404001C5354144E4DA40E01F5000002" ORGCODE="00010019" xmlns="Mytest/v1.0">
<STAT TIME="000000018" TYPE="SYS" FIELD="PWR_V" VAL="1196"/>
<STAT TIME="000000018" TYPE="CAN" NID="65" FIELD="LAST_EC" VAL="EC_HEARTBEAT_TIMEOUT"/>
<STAT TIME="000000018" TYPE="NWK" FIELD="W_RSSI" VAL="-85"/>
<EVT TIME="0000000017" TYPE="ACC" SUBTYPE="GRANTED" CRDT="DPIN" CRED1="1212"/>
<EVT TIME="0000000018" TYPE="ACC" SUBTYPE="GRANTED" CRDT="DPIN" CRED1="1212" CRED2="2345"/>
<EVT TIME="0000000019" TYPE="ACC" SUBTYPE="DENIED" CRDT="OCRD" CRED1="0000DE0871"/>
<EVT TIME="0000000020" TYPE="ACC" SUBTYPE="GRANTED" CRDT="DCRD" CRED1="0000DE0871" CRED2="2345"/>
<EVT TIME="0000000021" TYPE="CFG" SUBTYPE="RELOCK_TIME" VAL="300"/>
<EVT TIME="0000000022" TYPE="LOG" SUBTYPE="HB_TIMEOUT" VAL="65"/>
</ILS>
因此,在此板上搜索后,我发现以下问题回答了我的问题。但是,我应用了它,由于某种原因我根本无法得到任何结果,任何人都可以快速查看并指出我做错了什么吗?
public static void ParseXML(string data)
{
try
{
XDocument xDoc = XDocument.Parse(data);
XElement root = xDoc.Root;
Console.WriteLine("TGT: " + root.Attribute("TGT").Value + "\n");
Console.WriteLine("PID: " + root.Attribute("PID").Value + "\n");
Console.WriteLine("ORGCODE: " + root.Attribute("ORGCODE").Value + "\n");
Console.WriteLine("xmlns: " + root.Attribute("xmlns").Value + "\n");
//Everything above this line is good, I was able to get the print out.
var eleSTAT = from node in xDoc.Descendants("STAT")
select new
{
attrTIME = node.Attribute("TIME").Value,
attrTYPE = node.Attribute("TYPE").Value,
attrFIELD = node.Attribute("FIELD").Value,
attrVAL = node.Attribute("VAL").Value,
};
//When I run my code, it never got into this foreach loop, aas if eleSTAT is empty
foreach (var s in eleSTAT)
{
Console.WriteLine("TIME: " + s.attrTIME + "\n");
Console.WriteLine("TYPE: " + s.attrTYPE + "\n");
Console.WriteLine("FIELD: " + s.attrFIELD + "\n");
Console.WriteLine("VAL: " + s.attrVAL + "\n");
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
我的最后一个问题是,由于我有多个 STAT 元素,上述方法可行吗?我想让所有 4 个 STAT 元素及其属性返回给我。我认为这必须在某种类型的循环中完成?我是否正确地说我的 foreach 循环应该已经这样做了?