1

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.

Micha
  • 5,117
  • 8
  • 34
  • 47
tomtomssi
  • 1,017
  • 5
  • 20
  • 33

1 Answers1

0

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.

Community
  • 1
  • 1
Chuck Savage
  • 11,775
  • 6
  • 49
  • 69