亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何以有效的方式從字符串(xml)中獲取所需的子字符串?

如何以有效的方式從字符串(xml)中獲取所需的子字符串?

C#
慕少森 2022-11-13 15:51:23
我有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

        )

    )

);


查看完整回答
反對 回復 2022-11-13
  • 1 回答
  • 0 關注
  • 111 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號