0
votes

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);
}
3
"but when I create a node with element 'server'"... what does this mean?? Is there a reason you're using an XmlReader? Wouldn't it be easier to use LinqToXml? - spender
as you can see the node server has a lot of info, like name, country etc. but nothing is there in that node which I create by 'doc.ReadNode(reader)' No, there's no specific reason to use XmlReader. - moCap

3 Answers

2
votes

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?

1
votes

XmlReader is kind of low level for your needs...

Wouldn't it be easier to parse your XML with Linq2Xml?

var xmlStr = @"<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>";


var doc = XDocument.Parse(xmlStr);
var servers = doc.Root.Elements("server")
                 .Select(e => new{
                    name = (string)e.Attribute("name"),
                    ca = (int)e.Attribute("ca"),
                    country = (string)e.Attribute("country")
                    //etc...
                 });
0
votes

XmlDocument has method called "GetNodes", that will help you.