使用 LINQ to XML 对 XML 元素内的双引号进行编码
我正在将 XML 字符串解析为如下所示的 XDocument(使用 XDocument.Parse)
<Root>
<Item>Here is "Some text"</Item>
</Root>
然后我对 XML 进行了一些操作,我想将其作为字符串发送回,就像它传入一样
<Root>
<Item>Here is "Some text"</Item>
<NewItem>Another item</NewItem>
</Root>
但是,我我得到的是
<Root>
<Item>Here is \"Some text\"</Item>
<NewItem>Another item</NewItem>
</Root>
注意到双引号现在是如何转义而不是编码的?
无论我使用
ToString(SaveOptions.DisableFormatting);
还是
var stringWriter = new System.IO.StringWriter();
xDoc.Save(stringWriter, SaveOptions.DisableFormatting);
var newXml = stringWriter.GetStringBuilder().ToString();
如何让双引号显示为 "
而不是 \"
?
更新:可能会发生这种情况可以更好地解释它:
var origXml = "<Root><Item>Here is \"Some text"</Item></Root>";
Console.WriteLine(origXml);
var xmlDoc = System.Xml.Linq.XDocument.Parse(origXml);
var modifiedXml = xmlDoc.ToString(System.Xml.Linq.SaveOptions.DisableFormatting);
Console.WriteLine(modifiedXml);
我从中得到的输出是:
<Root><Item>Here is "Some text"</Item></Root>
<Root><Item>Here is "Some text"</Item></Root>
我希望输出是:
<Root><Item>Here is "Some text"</Item></Root>
<Root><Item>Here is "Some text"</Item></Root>
I'm parsing a string of XML into an XDocument that looks like this (using XDocument.Parse)
<Root>
<Item>Here is "Some text"</Item>
</Root>
Then I manipulate the XML a bit, and I want to send it back out as a string, just like it came in
<Root>
<Item>Here is "Some text"</Item>
<NewItem>Another item</NewItem>
</Root>
However, what I am getting is
<Root>
<Item>Here is \"Some text\"</Item>
<NewItem>Another item</NewItem>
</Root>
Notice how the double quotes are now escaped instead of encoded?
This happens whether I use
ToString(SaveOptions.DisableFormatting);
or
var stringWriter = new System.IO.StringWriter();
xDoc.Save(stringWriter, SaveOptions.DisableFormatting);
var newXml = stringWriter.GetStringBuilder().ToString();
How can I have the double quotes come out as "
and not \"
?
UPDATE: Maybe this can explain it better:
var origXml = "<Root><Item>Here is \"Some text"</Item></Root>";
Console.WriteLine(origXml);
var xmlDoc = System.Xml.Linq.XDocument.Parse(origXml);
var modifiedXml = xmlDoc.ToString(System.Xml.Linq.SaveOptions.DisableFormatting);
Console.WriteLine(modifiedXml);
the output I get from this is:
<Root><Item>Here is "Some text"</Item></Root>
<Root><Item>Here is "Some text"</Item></Root>
I want the output to be:
<Root><Item>Here is "Some text"</Item></Root>
<Root><Item>Here is "Some text"</Item></Root>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该使用
XmlWriter
确保字符编码正确。但是,我不确定您是否可以在不滚动自己的类来输出文本的情况下获得所需的确切输出。You should use an
XmlWriter
to ensure characters are encoded correctly. However, I'm not sure that you can get the exact output you want without rolling your own class to output the text.未经测试,不知道这是否适合您,但尝试
用此替换它
Not tested and don't know if this is solution for you, but try replacing this
with this