Home > Blockchain >  Cannot get XmlReader to recognize (insignificant)?whitespace
Cannot get XmlReader to recognize (insignificant)?whitespace

Time:12-25

I have the following example xml content for which I want to retain the whitespace between the two pairs of <p> elements. I would understand this to be insignificant whitespace.

<x>
  <p>Hello</p>

<p>How are you?</p></x>
XElement h = new XElement("x",
        new XElement("p", "Hello"),
        new XText("\n\n"),
        new XElement("p", "How are you?"));

The following code will output a single instance of ws found:

string p = "<x><p>Hello</p>\n\n<p>How are you?</p></x>";
StringReader sr = new StringReader(p);
    
XmlReader r = XmlReader.Create(sr, new XmlReaderSettings { IgnoreWhitespace = false });
    
while (r.Read())
{
    switch (r.NodeType)
    {
        case XmlNodeType.Whitespace:
            WriteLine("ws found");
            break;
        case XmlNodeType.SignificantWhitespace:
            WriteLine("sws found");
            break;
        default:
            break;
        }
    }
}

I guess I only get one output line because whitespace is normalized.

However, I want the same output using an XElement as the source rather than a string but below doesn't output anything:

XElement h = new XElement("x",
        new XElement("p", "Hello"),
        new XText("\n\n"),
        new XElement("p", "How are you?"));

XmlReader r = h.CreateReader();
    
while (r.Read())
{
    switch (r.NodeType)
    {
        case XmlNodeType.Whitespace:
            WriteLine("ws found");
            break;
        case XmlNodeType.SignificantWhitespace:
            WriteLine("sws found");
            break;
        default:
            break;
    }
}

I have tried including r.Settings.IgnoreWhitespace = false; but it doesn't help and is the default anyway.

Can anyone shed a light on how I can read and process the whitespace using XmlReader?

CodePudding user response:

It appears that the whitespace text nodes are being notified as XmlNodeType.Text.

  • Related