从XML文件中读取单个节点并将其用作条件

时间:2013-03-11 12:43:01

标签: c# xml-parsing

我只是尝试从XML读取特定节点并将其用作条件中的字符串变量。这让我得到了XML文件并给了我全部的东西。

string url = @"http://agent.mtconnect.org/current";
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(url);
        richTextBox1.Text = xmlDoc.InnerXml;

但是我需要“OFF”的电源状态“ON”(下面的XML部分,可以在线查看整个XML)

<Events><PowerState dataItemId="p2" timestamp="2013-03-11T12:27:30.275747" name="power" sequence="4042868976">ON</PowerState></Events>

我已经尝试过我所知道的一切。我对XML文件并不熟悉。而其他帖子让我无处可去。 请帮忙!

2 个答案:

答案 0 :(得分:2)

您可以尝试使用LINQ2XML:

  string value = (string) (XElement.Load("http://agent.mtconnect.org/current")
            .Descendants().FirstOrDefault(d => d.Name.LocalName == "PowerState"))

答案 1 :(得分:0)

如果您想避免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)。任何知道如何使这个更干净或更有效的人请发表评论。

编辑:

对于一个较低级别的'clunk',你可以改变这个:

if (CompStream.Attributes["component"].Value  == "Electric")
{
    Console.Out.WriteLine(((System.Xml.XmlElement)CompStream.SelectSingleNode("descendant::mtS:Events", theNameManager)).InnerText;);
    Console.In.Read();
}

因为那里只有一个元素,所以你会得到它innerText