Search code examples
c#xmlparsingnamespaceschildren

Inserting and removing nodes from an XML namespace


I'm trying to replace a node's name but I'm getting the following error "The reference node is not a child of this node". I think I know why this is happening but can't seem to work around this problem. Here is the XML:

 <payload:Query1 xmlns="" xmlns:payload="" xmlns:xsi="" xsi:schemaLocation="">
        <payload:QueryId>stuff</payload:QueryId>
        <payload:Data>more stuff</payload:Data>
 </payload:Query1>

And here is the C# bit:

doc.Load(readStream);
nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("payload", "location");
XmlNode Query1 = doc.SelectSingleNode("//payload:Query1", nsmgr);

public XmlDocument sendReply(args)
{
    XmlNode newNode = doc.CreateElement("payload:EditedQuery");
    Query.InsertBefore(newNode, Query1);
    Query.RemoveChild(Query1);
    return doc;
}

I'm trying to replace "Query" with "EditedQuery" but his doesn't work.


Solution

  • If you can use .Net 3.5 LINQ to XML,

    XElement root = XElement.Load(readStream);
    XNamespace ns = "http://somewhere.com";
    XElement Query1 = root.Descendants(ns + "Query1").FirstOrDefault();
    // should check for null first on Query1...
    Query1.ReplaceWith(new XElement(ns + "EditedQuery"));
    

    Or, if you don't know the namespace, or don't want to hard-code it:

    XElement root = XElement.Load(readStream);
    XElement Query1 = root.Descendants()
                          .FirstOrDefault(x => x.Name.Localname == "Query1");
    // should check for null first on Query1...
    Query1.ReplaceWith(new XElement(Query1.Name.Namespace + "EditedQuery"));
    

    See Jon Skeet's reason why to use LINQ to XML here over older API's.