我有C#申請。下面是我的字符串<subscription_add_ons type="array"> <subscription_add_on> <add_on_type>fixed</add_on_type> <add_on_code>bike-o-vision</add_on_code> <unit_amount_in_cents type="integer">2000</unit_amount_in_cents> <quantity type="integer">1</quantity> <revenue_schedule_type>evenly</revenue_schedule_type> </subscription_add_on> <subscription_add_on> <add_on_type>fixed</add_on_type> <add_on_code>boxx</add_on_code> <unit_amount_in_cents type="integer">1499</unit_amount_in_cents> <quantity type="integer">1</quantity> <revenue_schedule_type>evenly</revenue_schedule_type> </subscription_add_on> <subscription_add_on> <add_on_type>fixed</add_on_type> <add_on_code>fitfusion-strala</add_on_code> <unit_amount_in_cents type="integer">500</unit_amount_in_cents> <quantity type="integer">1</quantity> <revenue_schedule_type>evenly</revenue_schedule_type> </subscription_add_on></subscription_add_ons>我需要的是上面 xml 字符串的子字符串,如下所示。<subscription_add_ons type="array"> <subscription_add_on> <add_on_code>bike-o-vision</add_on_code> <quantity type="integer">1</quantity> </subscription_add_on> <subscription_add_on> <add_on_code>boxx</add_on_code> <quantity type="integer">1</quantity> </subscription_add_on> <subscription_add_on> <add_on_code>fitfusion-strala</add_on_code> <quantity type="integer">1</quantity> </subscription_add_on></subscription_add_ons>上面的代碼片段總是獲取第一個子字符串,對我來說它看起來非常低效。如何以有效的方式從字符串(xml)中獲取所需的子字符串?謝謝!
1 回答

萬千封印
TA貢獻1891條經驗 獲得超3個贊
只需解析 xml 并刪除不需要的元素:
XDocument doc = XDocument.Load("fileName.xml");
//or
//XDocument doc = XDocument.Parse(textString);
foreach(var removeNode in new string[]{"add_on_type", "unit_amount_in_cents","revenue_schedule_type"})
{
doc.Root.Descendants(removeNode).Remove();
}
string result = doc.ToString();
編輯:要添加更多元素,請這樣做:
doc.Root.Add(
new XElement(
"subscription_add_on",
new XElement("add_on_code","add_on_code_value"),
new XElement("quantity",
new XAttribute("type","integer"),
1
)
)
);
- 1 回答
- 0 關注
- 111 瀏覽
添加回答
舉報
0/150
提交
取消