从XML命名空间插入和删除节点

时间:2013-07-29 11:13:44

标签: c# xml parsing namespaces children

我正在尝试替换节点的名称但是我收到以下错误“参考节点不是此节点的子节点”。我想我知道为什么会这样,但似乎无法解决这个问题。这是XML:

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

这是C#位:

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

我正在尝试将“Query”替换为“EditedQuery”,但他的工作无效。

1 个答案:

答案 0 :(得分:0)

如果您可以使用.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"));

或者,如果您不知道命名空间,或者不想对其进行硬编码:

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"));

请参阅Jon Skeet的原因why to use LINQ to XML here over older API's