将 XmlDocument 转换为字符串
以下是我目前将 XMLDocument 转换为 String 的方法。
StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
xmlDoc.WriteTo(xmlTextWriter);
return stringWriter.ToString();
此方法的问题是,如果我有 " ((quotes)例如
:
<Campaign name="ABC">
</Campaign>
上面是预期的 XML,但它返回
<Campaign name=\"ABC\">
</Campaign>
我可以执行 String.Replace "\" 但这种方法可以吗?如果 XML 本身包含 "\",则可以正常工作
Here is how I'm currently converting XMLDocument to String
StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
xmlDoc.WriteTo(xmlTextWriter);
return stringWriter.ToString();
The problem with this method is that if I have " ((quotes) which I have in attributes) it escapes them.
For Instance:
<Campaign name="ABC">
</Campaign>
Above is the expected XML. But it returns
<Campaign name=\"ABC\">
</Campaign>
I can do String.Replace "\" but is that method okay? Are there any side-effects? Will it work fine if the XML itself contains a "\"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
假设 xmlDoc 是一个 XmlDocument 对象 xmlDoc.OuterXml 有什么问题?
OuterXml 属性 返回以下内容的字符串版本xml。
Assuming xmlDoc is an XmlDocument object whats wrong with xmlDoc.OuterXml?
The OuterXml property returns a string version of the xml.
没有任何报价。这只是VS调试器。尝试打印到控制台或保存到文件,您就会看到。附带说明:始终处理一次性物品:
There aren't any quotes. It's just VS debugger. Try printing to the console or saving to a file and you'll see. As a side note: always dispose disposable objects:
如果您使用的是
XmlDocument
的Windows.Data.Xml.Dom.XmlDocument
版本(例如在 UWP 应用中使用),则可以使用yourXmlDocument.GetXml()
以字符串形式获取 XML。If you are using
Windows.Data.Xml.Dom.XmlDocument
version ofXmlDocument
(used in UWP apps for example), you can useyourXmlDocument.GetXml()
to get the XML as a string.作为扩展方法:
现在简单地使用:
As an extension method:
Now to use simply:
"
在调试器中显示为\"
,但字符串中的数据是正确的,您不需要替换任何内容。尝试将字符串转储到文件中,您会发现该字符串是正确的。"
is shown as\"
in the debugger, but the data is correct in the string, and you don't need to replace anything. Try to dump your string to a file and you will note that the string is correct.您可以使用 xmlDoc.InnerXml 属性来获取字符串中的 xml
you can use
xmlDoc.InnerXml
property to get xml in string