[英]how to edit XML data within SOAP Request using C#?
I would like to edit xml data for one element with in SOAP request in order to send unique SOAP requests. 我想用SOAP请求中的一个元素编辑xml数据,以便发送唯一的SOAP请求。
Following is the example request 以下是示例请求
<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>
I would like to change "name" element value from "abcd 13071502" to "abcd ". 我想将“名称”元素值从“ abcd 13071502”更改为“ abcd”。 I was able to extract data from "name" element and edit the value by using following code in C#
我能够从“名称”元素中提取数据并通过使用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;
}
}
However, I couldn't figure out how to edit the value and save the file. 但是,我不知道如何编辑值和保存文件。 Any help would be appreciated.
任何帮助,将不胜感激。 Thank you.
谢谢。
Use the XmlDocument
class instead of the XmlTextReader
class. 使用
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");
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
To get Value
or InnerText
of a node, you will have to make sure the node exist. 要获取节点的
Value
或InnerText
,必须确保该节点存在。 The line string currentNameValue
has the format like this: 行
string currentNameValue
的格式如下:
var variable = condition ? A : B;
It's basically saying that if condition is true, then variable equals A, otherwise, variable equals B. 基本上是说,如果条件为true,则变量等于A,否则,变量等于B。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.