为什么复制XML节点时命名空间引用会丢失?

时间:2010-09-28 02:45:38

标签: .net xml infopath xml-namespaces

我有一个类似于此的XML文档(InfoPath表单):

<my:ClientMaintenance xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2009-07-06T07:04:54">
    <my:Payments>
    </my:Payments>
    <my:Payment>
        <my:Amount></my:Amount>
        <!-- Several other nodes -->
    </my:Payment>
</my:ClientMaintenance>

Payment节点用作模板,以向Payments节点添加新付款。因此,只要在表单上单击添加付款按钮,我就需要:

  1. 获取内存中Payment节点的副本
  2. 更新值
  3. 将其作为子项附加到Payments节点
  4. 由于某些原因,我无法再查询my命名空间中的任何节点!这是代码:

    public void btnAddPaymentClicked(object sender, ClickedEventArgs e)
    {
        var navigator = e.Source.CreateNavigator();
        var blankPayment = GetBlankPaymentNode(navigator).CreateNavigator();
        // new XmlNamespaceManager(blankPayment.NameTable).HasNamespace("my") == false
        // WHY???
    }
    
    private XmlDocument GetBlankPaymentNode(XPathNavigator navigator)
    {
        var blankPayment = navigator.SelectSingleNode(FullBlankPaymentXPath, NamespaceManager);
        var blankXml = new XmlDocument();
        blankXml.LoadXml(blankPayment.OuterXml);
        var schema = new XmlSchema();
        schema.Namespaces.Add("my", MyNamespaceUri);  // Set elsewhere and != null
        blankXml.Schemas.Add(schema);
        return blankXml;
    }
    

    为什么不再引用命名空间?

1 个答案:

答案 0 :(得分:2)

您需要将前缀显式添加到XmlNamespaceManager:

XPathNavigator blankPayment = GetBlankPaymentNode(navigator).CreateNavigator();
XmlNamespaceManager nsmngr = new XmlNamespaceManager(blankPayment.NameTable); 
nsmngr.AddNamespace("my", "http://schemas.microsoft.com/office/infopath/2003" + 
     "/myXSD/2009-07-06T07:04:54");

现在您可以通过前缀引用命名空间。