8

C# .net 2 または 3 で XmlDocument/XmlDeclaration クラスを使用しているときに、カスタム XmlDeclaration を作成したいと考えています。

これは私の目的の出力です (これは、サード パーティのアプリによって期待される出力です)。

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

カスタム XmlDeclaration を作成するために参照する必要がある XmlDocument/XmlDeclaration 以外のクラスはありますか? または、XmlDocument/XmlDeclaration クラス自体を使用する方法はありますか?

4

2 に答える 2

19

作成したいのはXML宣言ではなく「処理命令」です。XmlDeclarationクラスではなく、XmlProcessingInstruction クラス使用する必要があります。

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 に答える