I'm parsing a string of XML into an XDocument that looks like this (using XDocument.Parse)
我正在将一串XML解析为一个看起来像这样的XDocument(使用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
然后我稍微操纵了一下XML,我想把它作为一个字符串发回来,就像它进来一样
<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>
2 个解决方案
#1
2
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.
您应该使用XmlWriter来确保正确编码字符。但是,我不确定您是否可以获得所需的确切输出而无需滚动自己的类来输出文本。
#2
0
Not tested and don't know if this is solution for you, but try replacing this
没有经过测试,也不知道这是否适合您,但请尝试更换
var origXml = "<Root><Item>Here is \"Some text"</Item></Root>";
with this
var origXml = "<Root><Item>Here is \"Some text&quot;</Item></Root>";
#1
2
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.
您应该使用XmlWriter来确保正确编码字符。但是,我不确定您是否可以获得所需的确切输出而无需滚动自己的类来输出文本。
#2
0
Not tested and don't know if this is solution for you, but try replacing this
没有经过测试,也不知道这是否适合您,但请尝试更换
var origXml = "<Root><Item>Here is \"Some text"</Item></Root>";
with this
var origXml = "<Root><Item>Here is \"Some text&quot;</Item></Root>";