如何从字符串xml中删除第一个标记,c#

时间:2016-01-15 11:39:23

标签: c# xml string

我从网络服务获取数据。它返回一个包含xml标记的字符串:

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

现在我只想删除此字符串中的第一个<Amount>标记。这意味着我只想要这个

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

我该怎么做?

这就是我如何将webservice xml响应转换为字符串。

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

2 个答案:

答案 0 :(得分:2)

这是获得此结构的最简单方法:

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

但它完全硬编码。对于将来,您可以使用XmlSerializer将xml解析为c#对象,或者使用XSLT转换,这更易于实现。

答案 1 :(得分:0)

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