سؤال

The xml is coming from a url and all I need is the pull the string "N0014E1" from it. I am not sure why this code is not working. I put a try block around it and I get a "Data root level is invalid"

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# code:

    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();
    }
هل كانت مفيدة؟

المحلول

Your SelectNodes and SelectSingleNode commands are incorrect. Both expect an xpath string to identify the node.

Try the following

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);
}

Also, Note, that LoadXml method simply loads an xml string; it will not load from a remote url.

As @kevintdiy has pointed out your xml is not entirely correct. In the sample above I have stripped out the xsi reference as you are lacking a definition for it.

If you have access to the source xml, either remove the reference to xsi if its not required or add a definition for it to the root node.

If this is not possible, then you may want to consider using regular expression or other string based methods for getting the value.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top