我有一个xml soap文件,我需要在两个节点之间放置一个值:
<testedObject></testedObject>
<lsp></lsp>
我对冒号和访问上述元素有一些问题。 XML:
<SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP:Header>
<header xmlns="xmlapi_1.0">
<security>
<user>myusername</user>
<password>mypassword</password>
</security>
</header>
</SOAP:Header>
<SOAP:Body>
<sas.Test.adhocExecuteAndWait xmlns="xmlapi_1.0">
<deployer>mydeployer</deployer>
<synchronousDeploy>true</synchronousDeploy>
<testedObject></testedObject>
<test>
<mpls.LspPing>
<actionMask>
<bit>create</bit>
</actionMask>
<testTargetType>lsp</testTargetType>
<lsp></lsp>
<packetsToSend>45</packetsToSend>
<displayedName></displayedName>
</mpls.LspPing>
</test>
<timeout>300000</timeout>
<keepTest>true</keepTest>
</sas.Test.adhocExecuteAndWait>
</SOAP:Body>
</SOAP:Envelope>
到目前为止我所做的是:
XmlDocument xml = new XmlDocument();
xml.Load(@"C:\file.xml");
XmlNodeList xnList = xml.SelectNodes("SOAP:Envelope[@*]");
foreach (XmlNode xn in xnList)
{
XmlNode anode = xn.SelectSingleNode("SOAP:Body");
foreach (XmlNode item in anode)
{
XmlNode example = item.SelectSingleNode("sas.Test.adhocExecuteAndWait[@*]");
foreach (var item in collection)
{
}
}
}
我有冒号问题,老实说我坚持了。你能看看吗?
答案 0 :(得分:0)
如果您的目标是使输出看起来像这样:
<testedObject>John</testedObject>
<test>
<mpls.LspPing>
<actionMask>
<bit>create</bit>
</actionMask>
<testTargetType>lsp</testTargetType>
<lsp>John</lsp>
<packetsToSend>45</packetsToSend>
<displayedName></displayedName>
</mpls.LspPing>
</test>
然后我会做这样的事情:
XmlDocument xml = new XmlDocument();
xml.Load(@"C:\file.xml");
//create a namespace manager for the SOAP Namespace
XmlNamespaceManager ns = new XmlNamespaceManager(xml.NameTable);
ns.AddNamespace("SOAP", "http://schemas.xmlsoap.org/soap/envelope/");
//create a new node
XmlNode newNode = xml.CreateNode(XmlNodeType.Text, "John", "");
newNode.Value = "John";
//get the elements where do you want to add the new node
XmlNode testedObject = xml.SelectSingleNode("//*[starts-with(local-name(), 'testedObject')]", ns);
XmlNode lspNode = xml.SelectSingleNode("//*[starts-with(local-name(), 'lsp')]", ns);
//add the new node
testedObject.AppendChild(newNode.Clone());
lspNode.AppendChild(newNode.Clone());
修改强>
这里更好的教训是如何处理空白名称空间。点击here以获取参考。
提高效果的一种方法是使用local-name()='nodename'
代替starts-with
。