XMLTextReader does not read element content

static void ReadXml() { string a= null; double b= 0; double c= 0; XmlReader xmlReader = new XmlReader("Testxml.xml"); xmlReader. using (xmlReader) { if (xmlReader != null) { while (xmlReader.Read()) { if (xmlReader.NodeType == XmlNodeType.Element) { switch (xmlReader.Name) { case "a": a = xmlReader.ReadElementContentAsString(); break; case "b": b = double.Parse(xmlReader.ReadElementContentAsString()); break; case "c": c = double.Parse(xmlReader.ReadElementContentAsString()); break; } } } } } } 

TestXML Content:

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

Case b never hits. But if I add a space after the end element b, then case b will fall. Now, how to make it work without changing the xml file?

+6
c #
source share
1 answer

Here is the working version of your code. Specific issues that are fixed include:

  • new XmlReader does not compile . This is an abstract class. You should use an XmlTextReader or another XmlReader derived class.

  • b is not a valid double . You tried to convert a large hexadecimal number to a double, which is impossible. You can use NumberStyles.HexNumber in a Parse call, but not with a double , it must be long or int .

  • Double reading . You called Read() inside the loop, but then used the XmlReader.ReadXxx() methods. This caused reading unnecessary times and skipping nodes. This is actually the main problem you asked for. The following code tracks the last item found, and then waits until it reaches the Text node for processing. This is good for simple / flat documents, but for more complex ones, you need a better way to track the status of, for example, a state machine. Or use the DOM. Or LINQ.

     static void ReadXml() { string a = null; long b = 0; double c = 0; string text = "<a><b>26a83f12c782</b><c>128</c><d>12</d></a>"; string element = ""; 
     using (XmlReader xmlReader = new XmlTextReader(new StringReader(text))) { while (xmlReader.Read()) { if (xmlReader.NodeType == XmlNodeType.Element) { element = xmlReader.Name; } else if (xmlReader.NodeType == XmlNodeType.Text) { switch (element) { case "a": a = xmlReader.Value; Console.WriteLine("a: " + a); break; case "b": b = long.Parse(xmlReader.Value, NumberStyles.HexNumber); Console.WriteLine("b: " + b); break; case "c": c = double.Parse(xmlReader.Value); Console.WriteLine("c: " + c); break; } } } } 
    } >
+10
source share

All Articles