Skip to main content
 首页 » 编程设计

c#之未输出 XmlDocument 前缀

2024年02月20日12soundcode

我正在尝试将前缀添加到新 XMLDocument 中的几个 xmlnode(100% 从头开始​​创建,而不是从文件加载等)。

用最简单的术语来说,我有这个:

XmlDocument doc = new XmlDocument(); 
XmlElement RootElement = (XmlElement)doc.AppendChild(doc.CreateElement("root")); 
foreach (string line in CSV) 
{ 
    XmlElement navPointElement = (XmlElement) RootElement.AppendChild(doc.CreateElement("navPoint")); 
    XmlElement navPointTypeElement =(XmlElement) navPointElement.AppendChild(doc.CreateElement("type")); 
    navPointTypeElement.Prefix = "acp"; 
    navPointTypeElement.InnerText = nodeCount == 0 ? "cover" : "article"; 
} 

还有更多的代码,但这可以让您了解我在做什么。现在文档输出正常,但它完全跳过了前缀声明。我已经阅读了有关定义 namespace 的信息,但我尝试了以下操作但无济于事。

XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable); 
ns.AddNamespace("acp", "http://www.namespace.com"); 

我确信它很简单,但我找不到任何关于它的文档。 xmldocument 前缀的 MSDN 文档只是简单地添加前缀,就像我所做的一样,不需要命名空间(或者至少他们在代码示例中是这样显示的)。

非常感谢任何帮助:)

请您参考如下方法:

好吧,您确实需要一个命名空间。类似于 <acp:type/>本身无效,因为 acp不映射到任何命名空间,这是前缀应该做的。

您需要做的是在 type 的 CreateElement 调用中为要添加的元素设置 namespace 。元素。

public class StackOverflow_10807173 
{ 
    public static void Test() 
    { 
        XmlDocument doc = new XmlDocument(); 
        XmlElement RootElement = (XmlElement)doc.AppendChild( 
            doc.CreateElement("root")); 
        string[] CSV = "hello world how are you".Split(' '); 
        int nodeCount = 0; 
        XmlAttribute xmlnsAttr = doc.CreateAttribute( 
            "xmlns", "acp", "http://www.w3.org/2000/xmlns/"); 
        string acpNamespace = "http://www.namespace.com"; 
        xmlnsAttr.Value = acpNamespace; 
        RootElement.Attributes.Append(xmlnsAttr); 
        foreach (string line in CSV) 
        { 
            XmlElement navPointElement = (XmlElement)RootElement.AppendChild( 
                doc.CreateElement("navPoint")); 
            XmlElement navPointTypeElement = (XmlElement)navPointElement.AppendChild( 
                doc.CreateElement("type", acpNamespace)); // namespace here 
            navPointTypeElement.Prefix = "acp"; 
            navPointTypeElement.InnerText = nodeCount == 0 ? "cover" : "article"; 
        } 
 
        Console.WriteLine(doc.OuterXml); 
    } 
} 

请注意:您实际上不需要在根元素中添加 namespace ;只是如果你不这样做,你就会得到 xmlns:acp="yournamespace"所有 type 中的属性元素(因为该前缀不在范围内)。将其添加到父元素中就无需将其添加到子元素中。