views:

29

answers:

1

I have an XML document (an InfoPath form) that looks similar to this:

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

The Payment node is used as a template to add new payments to the Payments node. So whenever the Add Payment button is clicked on the form, I need to:

  1. Take a copy of the Payment node in memory
  2. Update the values
  3. Append it as a child to the Payments node

For some reason at the end of this, I can no longer query any nodes in the my namespace! Here's the code:

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

Why can the namespace no longer be referenced?

+2  A: 

Hi Alex,

You need to explicitly add the prefix to the 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");

Now you can reference the namespace by the prefix.

Rewinder
Thanks. If I lose the reference to XmlNamespaceManager, will `blankPayment.NameTable` still contain the `my` namespace?
Alex Angas
It will still contain the namespace, but you need a XmlNamespaceManager to access it. If you lose the reference, you could also instantiate a new one, and add the namespace again.
Rewinder
Thanks very much!
Alex Angas