简体   繁体   中英

How to remove only the first tag from a string xml, c#

I'm getting data from a web service. It returns a string with xml tags:

<price>
 <Amount>
      <Amount>100</Amount>
 </Amount>
</price>

Now I want remove only the first <Amount> tag from this string. that means I want only this

<price>
      <Amount>100</Amount>
</price>

How can I do that?

this is how I get webservice xml response in to a string.

string result = "";
string webserviceUrl ="somerl.";
WebClient client = new WebClient();
result = client.DownloadString(webserviceUrl);

Thats the simpliest way to get this structure:

var doc = XElement.Load("File1.xml");
var amounts = doc.Elements("Amount").ToList();
amounts.ForEach(x =>
{
    var element = x.Element("Amount");
    x.RemoveNodes();
    x.Value = element.Value;
});

But its totally hardcoded. For the future you can use parsing xml to c# objects with XmlSerializer or use XSLT transformations, which is more prefferable.

XmlDocument _doc = new XmlDocument();
_doc.LoadXml("<price><Amount><Amount>100</Amount></Amount></price>");

XmlDocument _newXmlDoc = new XmlDocument();
XmlNode _rootNode = _newXmlDoc.CreateElement("price");
_newXmlDoc.AppendChild(_rootNode);
XmlNode _priceNode = _newXmlDoc.CreateElement("Amount");
_priceNode.InnerText = _doc.LastChild.InnerText;
_rootNode.AppendChild(_priceNode);
Console.WriteLine(_newXmlDoc.OuterXml);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM