如何将xmlnamespace添加到xmldocument

Cru*_*lIO 14 c# xml xmldocument

我试图创建一个xml应该看起来像这样

<?xml version="1.0" encoding="iso-8859-1"?>
<MyTestSet xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Tests>
    <Test>
      <messaure>1</messaure>
      <height>4</height>
    </Test>
    <Test>
      <messaure>4</messaure>
      <height>53</height>
    </Test>
  </Tests>
</MyTestSet>
Run Code Online (Sandbox Code Playgroud)

创建测试或测试元素不是问题,但创建包含命名空间的"MyTestSet"的最佳方法是什么?我使用c#XMLDocument

Rob*_*Rob 29

这对我有用:

XmlDocument.DocumentElement.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
XmlDocument.DocumentElement.SetAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
Run Code Online (Sandbox Code Playgroud)

如果要创建已发布的整个文档,可能不想忘记XML声明:

        XmlDeclaration xml_declaration;
        xml_declaration = XmlDocument.CreateXmlDeclaration("1.0", "ISO-8859-1", "yes");

        XmlElement document_element = XmlDocument.DocumentElement;
        XmlDocument.InsertBefore(xml_declaration, document_element);
Run Code Online (Sandbox Code Playgroud)

在某些情况下,您可能需要它.