如何在C#中添加具有不同前缀/命名空间的xml属性?

Nar*_*ian 6 c# xml xml-attribute

我需要能够创建一个如下所示的XML Document:

 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <rootprefix:rootname 
     noPrefix="attribute with no prefix"
     firstprefix:attrOne="first atrribute"
     secondprefix:attrTwo="second atrribute with different prefix">

     ...other elements...

 </rootprefix:rootname>
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

XmlDocument doc = new XmlDocument();

XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
doc.AppendChild(declaration);

XmlElement root = doc.CreateElement("rootprefix:rootname", nameSpaceURL);
root.SetAttribute("schemaVersion", "1.0");

root.SetAttribute("firstprefix:attrOne", "first attribute");
root.SetAttribute("secondprefix:attrTwo", "second attribute with different prefix");

doc.AppendChild(root);
Run Code Online (Sandbox Code Playgroud)

不幸的是,我得到的带有第二个前缀的第二个属性根本没有前缀.它只是"attrTwo" - 就像schemaVersion属性一样.

那么,有没有办法在C#的根元素中为属性设置不同的前缀?

Azh*_*any 2

这只是为您提供的指南。也许你可以这样做:

        NameTable nt = new NameTable();
        nt.Add("key");

        XmlNamespaceManager ns = new XmlNamespaceManager(nt);
        ns.AddNamespace("firstprefix", "fp");
        ns.AddNamespace("secondprefix", "sp");

        root.SetAttribute("attrOne", ns.LookupPrefix("fp"), "first attribute");

        root.SetAttribute("attrTwo", ns.LookupPrefix("sp"), "second attribute with different prefix");
Run Code Online (Sandbox Code Playgroud)

这将导致:

        <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
        <rootprefix:rootname schemaVersion="1.0" d1p1:attrOne="first attribute" d1p2:attrTwo="second attribute with different prefix" xmlns:d1p2="secondprefix" xmlns:d1p1="firstprefix" xmlns:rootprefix="ns" />
Run Code Online (Sandbox Code Playgroud)

希望这会有帮助!