C# 如何使用 XmlDocument/XmlDeclaration 添加自定义 XmlDeclaration?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/334256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 23:36:39  来源:igfitidea点击:

How do I add a custom XmlDeclaration with XmlDocument/XmlDeclaration?

c#.netxmlxmldocument

提问by Metro Smurf

I would like to create a custom XmlDeclaration while using the XmlDocument/XmlDeclaration classes in c# .net 2 or 3.

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

This is my desired output (it is an expected output by a 3rd party app):

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

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

Using the XmlDocument/XmlDeclaration classes, it appears I can only create a single XmlDeclaration with a defined set of parameters:

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

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

Is there a class other than the XmlDocument/XmlDeclaration I should be looking at to create the custom XmlDeclaration? Or is there a way with the XmlDocument/XmlDeclaration classes itself?

除了 XmlDocument/XmlDeclaration 之外,是否还有其他类我应该查看以创建自定义 XmlDeclaration?或者有没有办法使用 XmlDocument/XmlDeclaration 类本身?

采纳答案by Bradley Grainger

What you are wanting to create is not an XML declaration, but a "processing instruction". You should use the XmlProcessingInstructionclass, not the XmlDeclarationclass, e.g.:

您要创建的不是 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);

回答by Oppositional

You would want to append a XmlProcessingInstructioncreated using the CreateProcessingInstructionmethod of the XmlDocument.

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

Example:

例子:

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);