gpt4 book ai didi

xml - 如何使 XMLDOMDocument 包含 XML 声明?

转载 作者:数据小太阳 更新时间:2023-10-29 01:44:33 25 4
gpt4 key购买 nike

当 XMLDOMDocument 保存自身时,我怎样才能让它包含 XML 声明,例如:

  • <?xml version="1.0" encoding="UTF-8" ?>
  • <?xml version="1.0" encoding="UTF-16" ?>
  • <?xml version="1.0" encoding="UCS-2" ?>
  • <?xml version="1.0" encoding="UCS-4" ?>
  • <?xml version="1.0" encoding="ISO-10646-UCS-2" ?>
  • <?xml version="1.0" encoding="UNICODE-1-1-UTF-8" ?>
  • <?xml version="1.0" encoding="UNICODE-2-0-UTF-16" ?>
  • <?xml version="1.0" encoding="UNICODE-2-0-UTF-8" ?>
  • <?xml version="1.0" encoding="US-ASCII" ?>
  • <?xml version="1.0" encoding="ISO-8859-1" ?>
  • <?xml version="1.0" encoding="WINDOWS-1250" ?>

正在内存中创建 XMLDOMDomcument 对象(即未从某些外部源加载 xml):

{
IXMLDOMDocument2 doc = new DOMDocument60();

//add nodes to the doc
...

doc.Save(saveTarget);
}

如果没有 xml 声明,您只会得到主体 xml,例如:

<Customer>
...
</Customer>

而不是完整的 XML 文档:

<?xml version="1.0" encoding="US-ASCII" ?>
<Customer>
...
</Customer>

问题2

我如何控制 encoding the XMLDOMDocument将在保存到流时使用?

最佳答案

您需要使用 MXXMLWriter60,而不是直接保存它。抱歉,我没有 C# 示例,但这是 VB.Net 的等效示例。参见 IMXWriter了解详情。

' Create and load a DOMDocument object.

Dim xmlDoc As New DOMDocument60
xmlDoc.loadXML("<doc><one>test1</one><two>test2</two></doc>")

' Set properties on the XML writer - including BOM, XML declaration and encoding

Dim wrt As New MXXMLWriter60
wrt.byteOrderMark = True
wrt.omitXMLDeclaration = False
wrt.encoding = "US-ASCII"
wrt.indent = True

' Set the XML writer to the SAX content handler.

Dim rdr As New SAXXMLReader60
Set rdr.contentHandler = wrt
Set rdr.dtdHandler = wrt
Set rdr.errorHandler = wrt
rdr.putProperty "http://xml.org/sax/properties/lexical-handler", wrt
rdr.putProperty "http://xml.org/sax/properties/declaration-handler", wrt

' Now pass the DOM through the SAX handler, and it will call the writer

rdr.parse xmlDoc

' Let the writer do its thing

Dim iFileNo As Integer
iFileNo = FreeFile
Open App.Path + "\saved.xml" For Output As #iFileNo
Print #iFileNo, wrt.output
Close #iFileNo

关于xml - 如何使 XMLDOMDocument 包含 XML 声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1144015/

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