【问题标题】:creating elements with namespace prefix based on multipart xml root declaration基于多部分 xml 根声明创建具有命名空间前缀的元素
【发布时间】:2013-03-08 18:05:15
【问题描述】:

如果我这样做:

System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
XmlElement e = xmlDoc.CreateElement("ShipmentReceiptNotification");
e.SetAttribute("xmlns", "urn:rosettanet:specification:interchange:ShipmentReceiptNotification:xsd:schema:02.02");
e.SetAttribute("xmlns:ssdh", "urn:rosettanet:specification:domain:Procurement:AccountClassification:xsd:codelist:01.03");
XmlNode ShipmentReceiptNotification0Node = e;

ShipmentReceiptNotification0Node.InnerText = String.Empty;
xmlDoc.AppendChild(ShipmentReceiptNotification0Node);
XmlNode DocumentHeader1Node = xmlDoc.CreateElement("ssdh:DocumentHeader");
ShipmentReceiptNotification0Node.AppendChild(DocumentHeader1Node);

会导致第二个节点ssdh的前缀不显示,只显示DocumentHeader。我该如何解决这个问题?

【问题讨论】:

    标签: c# xml xml-namespaces prefix


    【解决方案1】:

    你需要像这样创建它:

    XmlNode DocumentHeader1Node = xmlDoc.CreateElement("ssdh", "DocumentHeader", "urn:rosettanet:specification:domain:Procurement:AccountClassification:xsd:codelist:01.03");
    

    重点是XmlDocument需要知道哪个命名空间前缀(第一个参数)对应哪个命名空间URI(第三个参数)。有点违反直觉,但这就是它的工作方式。

    还要注意ShipmentReceiptNotification0Node.InnerText = String.Empty;这行是没用的;省略它是安全的,元素是空的默认情况下

    【讨论】:

    • 所以每次我有一个ssdh我都需要通过元素再次声明命名空间?
    • 是的。声明一个常量和一个辅助方法是个好主意……
    • 它也会导致 我更喜欢
    • 添加到xmlDoc后检查了吗?当我获取您的代码片段并用相应的 CreateElement 替换 *just 一行时,它按预期工作(=嵌套元素中没有重复的 xmlns:ssdh)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 2016-10-30
    • 2014-01-27
    相关资源
    最近更新 更多