从xml中拉出字符串

时间:2013-05-08 15:53:10

标签: c# xml url httpcontext

xml来自网址,我需要的只是拉字符串" N0014E1"从中。我不确定为什么这段代码不起作用。我在它周围试了一下,我得到了一个"数据根级别无效"

xml:

<obj is="c2g:Network " xsi:schemaLocation="http://obix.org/ns/schema/1.0/obi/xsd" href="http://192.168.2.230/obix/config/">
  <ref name="N0014E1" is="c2g:LOCAL c2g:Node"xsi:schemaLocation="http://obix.org/ns/sc/1.0/obix/xsd" href="N0014E1/"></ref>
</obj>

C#代码:

    public static string NodePath = "http://" + MainClass.IpAddress + ObixPath;


    public static void XMLData()
    {
        XmlDocument NodeValue = new XmlDocument();
        NodeValue.LoadXml(NodePath);


        var nodes = NodeValue.SelectNodes(NodePath);

        foreach (XmlNode Node in nodes)
        {
            HttpContext.Current.Response.Write(Node.SelectSingleNode("//ref name").Value);
            Console.WriteLine(Node.Value);
        }

        //Console.WriteLine(Node);
        Console.ReadLine();
    }

1 个答案:

答案 0 :(得分:0)

您的SelectNodesSelectSingleNode命令不正确。两者都期望使用xpath字符串来标识节点。

尝试以下

string xml = @"<obj is=""c2g:Network "" href=""http://192.168.2.230/obix/config/""><ref name=""N0014E1"" is=""c2g:LOCAL c2g:Node"" href=""N0014E1/""></ref></obj>";

XmlDocument NodeValue = new XmlDocument();
NodeValue.LoadXml(xml);
XmlNode r = NodeValue.SelectSingleNode("//ref[@name]");
if (r != null)
{
    System.Diagnostics.Debug.WriteLine(r.Attributes["name"].Value);
}

另外,注意,LoadXml方法只是加载一个xml字符串;它不会从远程URL加载。

正如@kevintdiy指出你的xml并不完全正确。在上面的示例中,我删除了xsi引用,因为您缺少定义。

如果您有权访问源xml,请删除对xsi的引用(如果不需要),或者将其定义添加到根节点。

如果无法做到这一点,那么您可能需要考虑使用正则表达式或其他基于字符串的方法来获取值。

相关问题