【问题标题】:How do I add a custom XmlDeclaration with XmlDocument/XmlDeclaration?如何使用 XmlDocument/XmlDeclaration 添加自定义 XmlDeclaration?
【发布时间】:2010-09-24 22:58:33
【问题描述】:

我想在 c# .net 2 或 3 中使用 XmlDocument/XmlDeclaration 类时创建自定义 XmlDeclaration。

这是我想要的输出(它是第 3 方应用程序的预期输出):

<?xml version="1.0" encoding="ISO-8859-1" ?>
<?MyCustomNameHere attribute1="val1" attribute2="val2" ?>
[ ...more xml... ]

使用 XmlDocument/XmlDeclaration 类,我似乎只能使用一组已定义的参数创建单个 XmlDeclaration:

XmlDocument doc = new XmlDocument();
XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "ISO-8859-1", null);
doc.AppendChild(declaration);

除了 XmlDocument/XmlDeclaration 之外,我还应该查看其他类来创建自定义 XmlDeclaration 吗?或者 XmlDocument/XmlDeclaration 类本身有什么办法?

【问题讨论】:

    标签: c# .net xml xmldocument


    【解决方案1】:

    您要创建的不是 XML 声明,而是“处理指令”。您应该使用 XmlProcessingInstruction 类,而不是 XmlDeclaration 类,例如:

    XmlDocument doc = new XmlDocument();
    XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "ISO-8859-1", null);
    doc.AppendChild(declaration);
    XmlProcessingInstruction pi = doc.CreateProcessingInstruction("MyCustomNameHere", "attribute1=\"val1\" attribute2=\"val2\"");
    doc.AppendChild(pi);
    

    【讨论】:

      【解决方案2】:

      您可能希望附加一个使用 XmlDocumentCreateProcessingInstruction 方法创建的 XmlProcessingInstruction

      例子:

      XmlDocument document        = new XmlDocument();
      XmlDeclaration declaration  = document.CreateXmlDeclaration("1.0", "ISO-8859-1", "no");
      
      string data = String.Format(null, "attribute1=\"{0}\" attribute2=\"{1}\"", "val1", "val2");
      XmlProcessingInstruction pi = document.CreateProcessingInstruction("MyCustomNameHere", data);
      
      document.AppendChild(declaration);
      document.AppendChild(pi);
      

      【讨论】:

      • @Oppositional - 再次感谢 :) 勇敢地,你们都成功了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-23
      • 1970-01-01
      • 1970-01-01
      • 2016-03-21
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      相关资源
      最近更新 更多