tags:

views:

76

answers:

1
<a><b>26a83f12c782</b><c>128</c><d>12</d></a>



 static void ReadXml1()
   {
       string b = null;
       double c = 0;
       double d = 0;

        using (XmlTextReader xmlReader = new XmlTextReader("Testxml.xml"))
       {
           if (xmlReader != null)
           {
               while (xmlReader.Read())
               {
                   if (xmlReader.NodeType == XmlNodeType.Element)
                   {
                       switch (xmlReader.Name)
                       {
                           case "b":
                               b = xmlReader.ReadElementContentAsString();

                               break;
                           case "c":
                               c = double.Parse(xmlReader.ReadElementContentAsString());

                               break;
                           case "d":
                               d = double.Parse(xmlReader.ReadElementContentAsString());

                               break;
                       }
                   }
               }
       }
           }

   }

The first line is in the Testxml.xml file. Case "c" is never hit. But if I add a space after </b> in xml file, it will work. But I can't change the xml file. So how do I get the value of c element.

+1  A: 

ReadElementContentAsString performs a read to move to the next node after consuming the content. In your code, you do an additional read, skipping over the next element declaration. In the case you provided, you can get away with out the while loop altogether, e.g.:

StringReader sr = new StringReader("<a><b>26a83f12c782</b><c>128</c><d>12</d></a>");
string b = null;
double c = 0;
double d = 0;
using (XmlReader xmlReader = XmlReader.Create(sr, new XmlReaderSettings() { IgnoreWhitespace = true }))
{
    xmlReader.MoveToContent();
    xmlReader.ReadStartElement("a", "");
    b = xmlReader.ReadElementContentAsString("b", "");
    c = xmlReader.ReadElementContentAsDouble("c", "");
    d = xmlReader.ReadElementContentAsDouble("d", "");
}
  • List item
leakyboat