簡體   English   中英

如何從字符串xml中僅刪除第一個標簽,C#

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

我正在從Web服務獲取數據。 它返回帶有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);

這就是獲得此結構的最簡單方法:

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轉換,這是更可取的。

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