XmlDocument doc = new XmlDocument();
string soapEnvelope =
@"<s:Envelope xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/"">
<s:Body xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<ExternalProcessingStatusUpdate xmlns=""http://tempuri.org/"">
<deliveryId>12232</deliveryId>
<success>true</success>
<message>Completed</message>
</ExternalProcessingStatusUpdate>
</s:Body>
</s:Envelope>";
doc.Load(new StringReader(soapEnvelope));
//Create a new node.
XmlElement elem = doc.CreateElement("orderId");
elem.InnerText = "ORDER_994865453";
XmlNode root = doc.DocumentElement;
var nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("rate", "http://www.w3.org/2001/XMLSchema");
var node = doc.SelectSingleNode("//rate:ExternalProcessingStatusUpdate", nsmgr);
doc.InsertAfter(elem, node.FirstChild);
我想在上面的Xml字符串中的“deliveryid”元素之后插入一个新元素“orderId”。我该如何解决这个问题?
答案 0 :(得分:0)
ExternalProcessingStatusUpdate
具有默认命名空间(xmlns="..."
),因此它和它没有前缀的后代元素都在该默认命名空间中。这意味着,新元素orderId
也应该在该命名空间中声明,否则它将在没有命名空间的情况下创建,如<orderId xmlns="">
,我认为这不是你真正想要的东西:
//Create a new node in "http://tempuri.org/" namespace
XmlElement elem = doc.CreateElement("", "orderId", "http://tempuri.org/");
elem.InnerText = "ORDER_994865453";
然后你应该在新节点的父节点上调用InsertAfter()
:
var nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("rate", "http://tempuri.org/");
var deliveryId = doc.SelectSingleNode("//rate:ExternalProcessingStatusUpdate/rate:deliveryId", nsmgr);
deliveryId.ParentNode.InsertAfter(elem, deliveryId);
<强> dotnetfiddle demo
强>