Search code examples
c#xmlxmlreader

Reading xml with XmlReader


Here is xml that I want to read

<servers>
   <server name=" PIOU PIOU || OPTIMAL" ca="1" continent_code="EU" 
           country="France" country_code="FR" ip="s1.mymumble.fr" 
           port="20129" region="" url="http://www.mymumble.fr" />
</servers>

Now when I read it I successfully get the elemnt 'servers' and I can read its innerxml as well i.e the correct node is created. but when I create a node with element 'server' the node is empty. I guess the reason is the short form of starting and ending element used in the 'server' node. But my problem is that the xml comes from some remote server and I cannot modify it, so I have to read it the way it is written.

Here is my code to read XML:

List<XmlNode> nodeList = new List<XmlNode>();
XmlDocument doc = new XmlDocument();

while (reader.Read())
{
    //keep reading until we see my element
    if (reader.Name.Equals("server") && (reader.NodeType == XmlNodeType.Element))
    {
        XmlNode myNode = doc.ReadNode(reader);
        Debug.Log(reader.IsEmptyElement ? "its empty" : "not empty");
        //this always prints "its empty"        
        nodeList.Add(myNode);
    }        
}

foreach( XmlNode node in nodeList)
{
    Debug.Log("child:\t"+node.FirstChild.InnerXml);
}

Solution

  • See the documentation for IsEmptyElement. In particular, this example:

    <item num="123"/> (IsEmptyElement is true).
    <item num="123"></item> (IsEmptyElement is false, although element content is empty).
    

    Your node is considered empty because it uses the short form. There is no element "content," but there are attributes.

    Have you checked the node that you created (i.e. myNode) to see that it contains the attributes?