我想在c#.net 2或3中使用XmlDocument/XmlDeclaration类时创建自定义XmlDeclaration.
这是我想要的输出(这是第三方应用程序的预期输出):
[ ...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类本身?
您想要创建的不是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);
您可能希望附加使用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);