如何使用C#在SOAP Request中编辑XML数据?

时间:2013-07-23 14:04:57

标签: c# xml soap

我想在SOAP请求中编辑一个元素的xml数据,以便发送唯一的SOAP请求。

以下是示例请求

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"xmlns:web="http://webservice/">
   <soapenv:Header/>
   <soapenv:Body>
      <web:ca>
         <type1>
            <ad>2013-07-19</ad>
            <name>abcd 13071502</name>
            <taker>
               <taker>TEST</taker>
               <emailAddress>test@test.com</emailAddress>
               <name>nameTest</name>
               <phoneNo>007007007</phoneNo>
               <takerUid>1234</takerUid>
            </taker>
         </type1>
         <type2>4</type2>
         <type3>peace</type3>
         <type4>test</type4>
      </web:ca>
   </soapenv:Body>
</soapenv:Envelope>

我想将“name”元素值从“abcd 13071502”更改为“abcd”。我能够从“name”元素中提取数据,并使用C#

中的以下代码编辑该值
System.Xml.XmlTextReader xr = new XmlTextReader(@filePath);
while (xr.Read())
{
if (xr.LocalName == "name")
    {
        xr.Read();
        currentNameValue = xr.Value;
        int cnvLen = currentNameValue.Length;
        string cnvWOdate = currentNameValue.Substring(0, cnvLen-8);
        string newNameValue = cnvWOdate+currTimeDate;
        break;
    }
}

但是,我无法弄清楚如何编辑值并保存文件。任何帮助,将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:1)

使用XmlDocument类而不是XmlTextReader类。

System.Xml.XmlDocument xd = new XmlDocument();
xd.Load(@"filepath");

foreach(XmlNode nameNode in xd.GetElementsByTagName("name"))
{
    if(nameNode.ParentNode.Name == "type1")
    {
        string currentNameValue = nameNode.InnerText;
        int cnvLen = currentNameValue.Length;
        string cnvWOdate = currentNameValue.Substring(0,cnvLen-8);
        string newNameValue = cnvWOdate+currTimeDate;

        nameNode.InnerText = newNameValue;
    }
}

xd.Save(@"newFilePath");

答案 1 :(得分:0)

XmlDocument doc = new XmlDocument();
doc.Load("file path");

XmlNode nameNode = doc.SelectSingleNode("/Envelope/Body/ca/type1/name");

string currentNameValue = nameNode != null ? nameNode.InnerText : "name not exist";
int cnvLen = currentNameValue.Length;
string cnvWOdate = currentNameValue.Substring(0, cnvLen-8);
string newNameValue = cnvWOdate+currTimeDate;

nameNode.InnerText = newNameValue; //set new value to tag

要获取节点的ValueInnerText,您必须确保该节点存在。第string currentNameValue行的格式如下:

var variable = condition ? A : B;

基本上说如果条件为真,则变量等于A,否则变量等于B.