Search code examples
xmlxmlreader

ReadString method of XmlReader removes/ignore CDATA tag


I'm getting a very strange behavior and unable to identify the issue. In following code snippet expected out was

<![CDATA[<air:FareInfo Key="10T"></air:FareInfo>/>]]>

but I'm getting

<air:FareInfo Key="10T"></air:FareInfo>/>

why CDATA tag is missing in output? I'm simply using XmlReader.ReadString() and it ignores CDATA tag.

 string xml = "<FareInfo>" + 
        "<![CDATA[<air:FareInfo Key=\"10T\">" + 
            "</air:FareInfo>/>]]>" + 
        "</FareInfo>";

        Encoding encoding = new UTF8Encoding();
        byte[] buffer = encoding.GetBytes(xml);
        MemoryStream stream = new MemoryStream(buffer);

        XmlReaderSettings settings = new XmlReaderSettings();
        XmlReader reader = XmlReader.Create(stream, settings);

        reader.Read();

        string output = reader.ReadString();

        Console.Write(output);

Any help in this regard will be highly appreciable.


Solution

  • Do this way:-

     switch (reader.NodeType) {
          case XmlNodeType.Text:
              Console.Write(reader.Value);
              break;
           case XmlNodeType.CDATA:
               Console.Write("<![CDATA[{0}]]>", reader.Value);
               break;
     }