如何使用 XmlWriter 在元素中编写命名空间

How to write a namespace in an Element with XmlWriter

我正在将我的代码从 vbs 更改为 C#,但我对 XMLwriter 有疑问,如何使用 XML write 在 XML.file 中获得这样的输出:? ?

我有这样的代码:

using (XmlWriter writer = XmlWriter.Create(Form1.systemDrive + "\unattend.xml"))
{
    writer.WriteStartDocument();
    writer.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
    writer.WriteStartElement("unattend");
    writer.WriteAttributeString("xmlns", "urn:schemas-microsoft-com:unattend"); // <<<<<<< Gives an error 

.....

如果您只想将无人参与标记放入给定的命名空间,则根本不要使用 WriteAttributeString,只需使用

writer.WriteStartElement("unattend","urn:schemas-microsoft-com:unattend");

如果命名空间被分配给一个前缀,它将使用该前缀,否则将生成必要的 xmlns 子句。

此外,WriteStartDocumentWriteProcessingInstruction 是多余的。两者产生相同的输出,但你只能有一个处理指令,所以你可以使用其中一个,但不能同时使用两个。