Search code examples
c#xmlwcfc#-4.0xmlreader

How to read the text element of an XML node without dereferencing entities using XmlReader


I am attempting to read a XML document containing elements like the data mentioned below.

Accessing the text node via reader.Value, reader.ReadContentAsString(), reader.ReadContentAsObject() results in the value read being truncated to the last ampersand, so in the case of the data below that would be ISO^urn:ihe:iti:xds:2013:referral. Using XmlDocument the text nodes can be read properly so I am assuming there has to be a way to make this work using the reader as well.

 <Slot name="urn:ihe:iti:xds:2013:referenceIdList">
              <ValueList>
                <Value>123456^^^&amp;orgID&amp;ISO^urn:ihe:iti:xds:2013:referral</Value>
                <Value>098765^^^&amp;orgID&amp;ISO^urn:ihe:iti:xds:2013:referral</Value>
              </ValueList>
            </Slot>


Clarification Edit

After asking the question I was able to determine my issue came from creating an XmlReader from a XPathNavigator instance created from a MessageBuffer executing in the context of a WCF service call. Thus @DarkGray's answer was correct for the original question but did not really address the root of the problem. I provided a second answer which addressed my corner case.

System.ServiceModel.Channels.Message message; // the inbound SOAP message
var buffer = message.CreateBufferedCopy(11 * 1024 * 1024);
var navigator = buffer.CreateNavigator();
var reader = navigator.ReadSubtree();
// advance the reader to the text element
//
// `reader.Value` now produces ISO^urn:ihe:iti:xds:2013:referral

Solution

  • Answer: reader.Value

    Output:

    123456^^^&orgID&ISO^urn:ihe:iti:xds:2013:referral
    098765^^^&orgID&ISO^urn:ihe:iti:xds:2013:referral
    

    Example:

    public static void Execute()
    {
      var xml = @"
        <Slot name='urn:ihe:iti:xds:2013:referenceIdList'>
          <ValueList>
            <Value>123456^^^&amp;orgID&amp;ISO^urn:ihe:iti:xds:2013:referral</Value>
            <Value>098765^^^&amp;orgID&amp;ISO^urn:ihe:iti:xds:2013:referral</Value>
          </ValueList>
        </Slot>
      ";
      var reader = System.Xml.XmlReader.Create(new System.IO.StringReader(xml));
      for (; ; )
      {
        if (!reader.Read())
          break;
        if (reader.NodeType == System.Xml.XmlNodeType.Text)
          Console.WriteLine(reader.Value);
      }
    }