如何使XMLDOMDocument包含XML声明?

前端之家收集整理的这篇文章主要介绍了如何使XMLDOMDocument包含XML声明?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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不是从某些外部源加载的):

  1. {
  2. IXMLDOMDocument2 doc = new DOMDocument60();
  3.  
  4. //add nodes to the doc
  5. ...
  6.  
  7. doc.Save(saveTarget);
  8. }

如果没有xml声明,你只能得到正文xml,例如:

  1. <Customer>
  2. ...
  3. </Customer>

而不是完整的XML文档:

  1. <?xml version="1.0" encoding="US-ASCII" ?>
  2. <Customer>
  3. ...
  4. </Customer>

问题2

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

您需要使用MXXMLWriter60,而不是直接保存它.对不起,我没有C#示例,但这里是VB.Net的等价物.有关详情,请参见 IMXWriter.
  1. ' Create and load a DOMDocument object.
  2.  
  3. Dim xmlDoc As New DOMDocument60
  4. xmlDoc.loadXML("<doc><one>test1</one><two>test2</two></doc>")
  5.  
  6. ' Set properties on the XML writer - including BOM,XML declaration and encoding
  7.  
  8. Dim wrt As New MXXMLWriter60
  9. wrt.byteOrderMark = True
  10. wrt.omitXMLDeclaration = False
  11. wrt.encoding = "US-ASCII"
  12. wrt.indent = True
  13.  
  14. ' Set the XML writer to the SAX content handler.
  15.  
  16. Dim rdr As New SAXXMLReader60
  17. Set rdr.contentHandler = wrt
  18. Set rdr.dtdHandler = wrt
  19. Set rdr.errorHandler = wrt
  20. rdr.putProperty "http://xml.org/sax/properties/lexical-handler",wrt
  21. rdr.putProperty "http://xml.org/sax/properties/declaration-handler",wrt
  22.  
  23. ' Now pass the DOM through the SAX handler,and it will call the writer
  24.  
  25. rdr.parse xmlDoc
  26.  
  27. ' Let the writer do its thing
  28.  
  29. Dim iFileNo As Integer
  30. iFileNo = FreeFile
  31. Open App.Path + "\saved.xml" For Output As #iFileNo
  32. Print #iFileNo,wrt.output
  33. Close #iFileNo

猜你在找的XML相关文章