gpt4 book ai didi

c# - 在c#中将特殊字符写入xml

转载 作者:太空宇宙 更新时间:2023-11-03 19:28:12 25 4
gpt4 key购买 nike

我正在使用 LINQ to XML 将元素写入 xml 文档。我遇到的问题是我尝试写入 xml 元素的字符串包含 &、<、> 和 ".

当我使用下面的代码将它写入 xml 时,

XElement Config= new XElement("Student", new XElement("ID", "><&\""));

我没有将这些特殊字符写入 XML 文档。相反,我得到类似 &lt; for < and &gt; for > 的东西.如何在将这些字符写入 xml 时转义这些字符?

谢谢

最佳答案

XDocument 自己转义它们。

<Student><ID>><&"</ID></Student>不是格式正确的 XML。

生成 XDocument 的格式正确的版本是:

<Student>
<ID>&gt;&lt;&amp;"</ID>
</Student>

您可以使用此代码(使用 CDATA):

XElement Config = new XElement("Student", new XElement("ID", new XCData("><&\"")));

输出:

<Student>
<ID><![CDATA[><&"]]></ID>
</Student>

关于c# - 在c#中将特殊字符写入xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6996627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com