8

我想在 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 类本身有没有办法?

4

2 回答 2

19

您要创建的不是 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);
于 2008-12-02T15:19:29.197 回答
5

您可能希望附加使用XmlDocument的CreateProcessingInstruction方法创建的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);
于 2008-12-02T15:26:04.160 回答