0

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();
    }
kevintdiy
  • 181
  • 2
  • 5
  • 13
  • 1
    Looks like there should be a space between `obj` and `is`? – zimdanen May 08 '13 at 15:56
  • 1
    Is that the entirety of the XML? If it is, it's invalid XML, which is why you're getting the error. The start tag is objis, and the closing tag is obj - the start and closing tag must match. – Tim May 08 '13 at 15:56
  • there is a space between obj and is, it just didnt copy, sorry about that. and yes this is the whole xml page. – kevintdiy May 08 '13 at 16:01

1 Answers1

0

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.

Kami
  • 19,134
  • 4
  • 51
  • 63