【问题标题】:How can I add xml attributes with different prefixes/namespaces in C#?如何在 C# 中添加具有不同前缀/命名空间的 xml 属性?
【发布时间】:2013-06-30 00:06:13
【问题描述】:

我需要能够创建如下所示的 XML 文档:

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

这是我的代码:

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

不幸的是,我得到的带有第二个前缀的第二个属性根本没有前缀。它只是“attrTwo”——类似于 schemaVersion 属性。

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

【问题讨论】:

    标签: c# xml xml-attribute


    【解决方案1】:

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

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

    这将导致:

            <?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" />
    

    希望这会有所帮助!

    【讨论】:

    • 值得注意的是,仅当您需要确定命名空间的简写而不是默认命名约定(d1p1、d1p2、...)时才需要 NameTable 和 AddNameSpace
    【解决方案2】:

    我看到a post on another question 最终解决了这个问题。我基本上只是创建了一个包含所有 xml 的字符串,然后在 XmlDocument 的实例上使用了 LoadXml 方法。

    string rootNodeXmlString = "<?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\" />";
    doc.LoadXml(rootNodeXmlString);
    

    【讨论】:

    • 这是最快的解决方案。谢谢你。我也这样做了,后来我用所需的 XML 替换了 InnerXml。我认为使用标准 API 以您想要的方式自定义输出非常困难。您无法控制写入属性的顺序。
    猜你喜欢
    • 2018-07-12
    • 1970-01-01
    • 2012-05-27
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多