5

我正在将一串 XML 解析成一个看起来像这样的 XDocument(使用 XDocument.Parse)

<Root>
  <Item>Here is &quot;Some text&quot;</Item>
</Root>

然后我稍微操作一下 XML,我想把它作为一个字符串发送回来,就像它进来一样

<Root>
  <Item>Here is &quot;Some text&quot;</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();

我怎样才能有双引号出来&quot;而不是\"

更新:也许这可以更好地解释它:

var origXml = "<Root><Item>Here is \"Some text&quot;</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&quot;</Item></Root>
<Root><Item>Here is "Some text"</Item></Root>

我希望输出为:

<Root><Item>Here is "Some text&quot;</Item></Root>
<Root><Item>Here is "Some text&quot;</Item></Root>
4

2 回答 2

2

您应该使用 anXmlWriter来确保字符被正确编码。但是,我不确定您是否可以在不滚动自己的类来输出文本的情况下获得所需的确切输出。

于 2010-04-05T14:50:55.437 回答
0

未经测试,不知道这是否适合您,但尝试替换它

var origXml = "<Root><Item>Here is \"Some text&quot;</Item></Root>";

有了这个

var origXml = "<Root><Item>Here is \"Some text&amp;quot;</Item></Root>";
于 2010-03-27T00:52:19.577 回答