如果你想避免LINQ,或者如果它不爲你工作,你可以使用直XML遍歷此:
string url = @"http://agent.mtconnect.org/current";
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
xmlDoc.Load(url);
System.Xml.XmlNamespaceManager theNameManager = new System.Xml.XmlNamespaceManager(xmlDoc.NameTable);
theNameManager.AddNamespace("mtS", "urn:mtconnect.org:MTConnectStreams:1.2");
theNameManager.AddNamespace("m", "urn:mtconnect.org:MTConnectStreams:1.2");
theNameManager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
System.Xml.XmlElement DeviceStreams = (System.Xml.XmlElement)xmlDoc.SelectSingleNode("descendant::mtS:DeviceStream", theNameManager);
System.Xml.XmlNodeList theStreams = DeviceStreams.SelectNodes("descendant::mtS:ComponentStream", theNameManager);
foreach (System.Xml.XmlNode CompStream in theStreams)
{
if (CompStream.Attributes["component"].Value == "Electric")
{
System.Xml.XmlElement EventElement = (System.Xml.XmlElement)CompStream.SelectSingleNode("descendant::mtS:Events", theNameManager);
System.Xml.XmlElement PowerElement = (System.Xml.XmlElement)EventElement.SelectSingleNode("descendant::mtS:PowerState", theNameManager);
Console.Out.WriteLine(PowerElement.InnerText);
Console.In.Read();
}
}
當遍歷根節點中具有默認名稱空間的任何文檔,我發現有一個命名空間管理器是必要的。沒有它,這個文件就是不可導航的。
我在控制檯應用程序中創建了此代碼。它爲我工作。我也不是大師,我可能會在這裏犯一些錯誤。我不確定是否有某種方法可以引用缺省命名空間而不用命名它(mtS)。任何知道如何使這個更清潔或更高效的人請評論。
編輯:因爲只有一個元素在那裏,其innerText
是所有你會得到
if (CompStream.Attributes["component"].Value == "Electric")
{
Console.Out.WriteLine(((System.Xml.XmlElement)CompStream.SelectSingleNode("descendant::mtS:Events", theNameManager)).InnerText;);
Console.In.Read();
}
:
對於「悶響」少了一個級別,你可以改變這一點。
您可能想要查看XPath。這就像XML的SQL。 – JDB 2013-03-11 12:46:51
請參閱以下文章: http://stackoverflow.com/questions/670563/linq-to-read-xml – 2013-03-11 12:48:13