我该如何更改” &quot到' '在xmldocument c#中?
当前,我有一个代码项目,可以将数据从Excel转换为XML,并且我正在使用XMLDOCUMEMENT将XML文件写入可用软件中的testcase。但是在运行XML时,它只会收到。
<?xml版本='1.0'encoding ='utf -8'?>
当我使用xmldocument的createxmldeclaration函数时,
XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("'1.0", "'utf-8'", null);
我的结果 - > <?xml版本=“ 1.0” encoding =“ utf-8”?>
我尝试修改它<?xml版本=“'1.0''1.0'condoding =“'utf-- 8'?>
,我得到了例外:
在 system.xml.dll错误的XML版本信息。 XML必须匹配 生产“版本” :: ='1.' [0-9]+“。
我如何在createxmldeclaration中使用''或将另一个API用作Xmldocument的替代方案?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您在这里有几个问题:
无需手动将XML声明添加到
或调用
xmldocument
通过调用creationexmldeclaration(creationexmldeclaration() 。当您调用
xmldocument.save()
。当您检查代码> outerxmlxmldocument.writocument.writeTo(writocument.writeto() a>。
写XML时使用 您可以通过设置 [1] 。
请注意,此属性同时控制了XML声明中使用的报价字符,也控制了用于属性值的报价字符。
还请注意,
XMLTEXTWRITER
已被弃用而不是致电xmlwriter.create()
,似乎没有一种使用xmlWriterSettings
。因此,如果您想对XML声明和属性值都使用单个报价字符,则可以介绍以下扩展方法:
,对于xml
< foo name =“ Hello”> bar ID =“ 101”> var value</bar></foo>
,方法doc.getOuterxml(quodechar:'\'')
将生成:demo fiddle#1 在这里a>。
请注意,单引号字符均用于XML声明和属性值。您的问题尚不清楚,但是如果您需要XML声明仅和双引号,否则您将需要子类
xmltextwriter
so:现在
现在
doc.getouterxml()
将返回:演示小提琴#2 在这里。
[1] 请参阅这个答案 by Peter Ritchie to 一个可以强制XMLWriter以单引号写元素?
You have a couple of issues here:
There is no need to manually add an XML Declaration to an
XmlDocument
by callingCreateXmlDeclaration()
. The XML Declaration will be written automatically using the current encoding when you call one of the overloads ofXmlDocument.Save()
. It will not be written when you inspect the value ofOuterXml
or callXmlDocument.WriteTo()
.When writing XML using
XmlTextWriter
you may control the quote character by settingXmlTextWriter.QuoteChar = '\''
[1].Note that this property controls both the quote character used in the XML declaration, and the quote character used for attribute values.
Note also that, while
XmlTextWriter
has been deprecated in favor of callingXmlWriter.Create()
, there does not appear to be a way to set the quote character usingXmlWriterSettings
.Thus, if you want to use a single quote character for both the XML declaration and attribute values, you can introduce the following extension method:
And, for the XML
<foo Name="hello"><bar Id="101">var value</bar></foo>
, the methoddoc.GetOuterXml(quoteChar : '\'')
will generate:Demo fiddle #1 here.
Notice that the single quote character is used for both the XML declaration and attribute values. Your question is unclear, but if you need a single quote for the XML Declaration only and double quotes otherwise, you will need to subclass
XmlTextWriter
like so:And now
doc.GetOuterXml()
will return:Demo fiddle #2 here.
[1] See this answer by Peter Ritchie to Can one force XMLWriter to write elements in single quotes?