开发者

why is XLinq reformatting my XML?

开发者 https://www.devze.com 2023-02-24 03:53 出处:网络
I am using XLinq (XML to Linq) to parse a xml document and one part of the document deals with representing rich-text and uses the xml:space=\"preserve\" attribute to preserve whitespace within the ri

I am using XLinq (XML to Linq) to parse a xml document and one part of the document deals with representing rich-text and uses the xml:space="preserve" attribute to preserve whitespace within the rich-text element.

The issue I'm experiencing is that when I have a element inside the rich-text which only contains a sub-element but no text, XLinq reformats the xml and puts the element on its own line. This, of course, causes additional white space to be created which changes the original content.

Example:

<rich-text xml:space="preserve">
    <text-run><br/></text开发者_JAVA技巧-run>
</rich-text>

results in:

<rich-text xml:space="preserve">
    <text-run>
        <br/>
    </text-run>
</rich-text>

If I add a space or any other text before the <br/> in the original xml like so

<rich-text xml:space="preserve">
    <text-run> <br/></text-run>
</rich-text>

the parser doesn't reformat the xml

<rich-text xml:space="preserve">
    <text-run> <br/></text-run>
</rich-text>

How can I prevent the xml parser from reformatting my element?

Is this reformatting normal for XML parsing or is this just an unwanted side effect of the XLinq parser?

EDIT: I am parsing the document like this:

using (var reader = System.Xml.XmlReader.Create(stream))
    return XElement.Load(reader);

I am not using any custom XmlReaderSettings or LoadOptions

The problem occurs when I use the .Value property on the text-run XElement to get the text value of the element. Instead of receiving \n which would be the correct output from the original xml, I will receive

\n \n

Note the additional whitespace and line break due to the reformatting! The reformatting can also be observed when inspecting the element in the debugger or calling .ToString().


Have you tried this:

yourXElement.ToString(SaveOptions.DisableFormatting)

This should solve your problem.

btw - you should also do a similar thing on load:

XElement.Parse(sr, LoadOptions.PreserveWhitespace);
0

精彩评论

暂无评论...
验证码 换一张
取 消