使用 LINQ to XML 在 XML 元素内编码双引号

dav*_*aro 5 c# xml encoding linq-to-xml double-quotes

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

<Root>
  <Item>Here is &quot;Some text&quot;</Item>
</Root>
Run Code Online (Sandbox Code Playgroud)

然后我对 XML 进行了一些操作,我想将它作为字符串发送回来,就像它进来一样

<Root>
  <Item>Here is &quot;Some text&quot;</Item>
  <NewItem>Another item</NewItem>
</Root>
Run Code Online (Sandbox Code Playgroud)

然而,我得到的是

<Root>
  <Item>Here is \"Some text\"</Item>
  <NewItem>Another item</NewItem>
</Root>
Run Code Online (Sandbox Code Playgroud)

注意双引号现在是如何转义而不是编码的?

无论我使用

ToString(SaveOptions.DisableFormatting);
Run Code Online (Sandbox Code Playgroud)

或者

var stringWriter = new System.IO.StringWriter();
xDoc.Save(stringWriter, SaveOptions.DisableFormatting);
var newXml = stringWriter.GetStringBuilder().ToString();
Run Code Online (Sandbox Code Playgroud)

我怎样才能让双引号出现&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);
Run Code Online (Sandbox Code Playgroud)

我从中得到的输出是:

<Root><Item>Here is "Some text&quot;</Item></Root>
<Root><Item>Here is "Some text"</Item></Root>
Run Code Online (Sandbox Code Playgroud)

我希望输出是:

<Root><Item>Here is "Some text&quot;</Item></Root>
<Root><Item>Here is "Some text&quot;</Item></Root>
Run Code Online (Sandbox Code Playgroud)

小智 0

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

var origXml = "<Root><Item>Here is \"Some text&quot;</Item></Root>";
Run Code Online (Sandbox Code Playgroud)

有了这个

var origXml = "<Root><Item>Here is \"Some text&amp;quot;</Item></Root>";
Run Code Online (Sandbox Code Playgroud)