简体   繁体   English

如何从字符串xml中仅删除第一个标签,C#

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

I'm getting data from a web service. 我正在从Web服务获取数据。 It returns a string with xml tags: 它返回带有xml标签的字符串:

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

Now I want remove only the first <Amount> tag from this string. 现在,我只想从此字符串中删除第一个<Amount>标记。 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. 这就是我如何将Webservice xml响应输入字符串。

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. 将来,您可以使用XmlSerializer将xml解析为c#对象,或者使用XSLT转换,这是更可取的。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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