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

问题描述 投票:0回答:1

我有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>

我试着得到如下。

var xml = _xml.GetXmlNodes(xmlString);
StringBuilder sb = new StringBuilder();
sb.Append("<subscription>");
foreach (XmlNode node in xml)
{
  var sIndex = node.OuterXml.IndexOf("<add_on_code>");
  var eIndex = node.OuterXml.IndexOf("</add_on_code>");
  var subs = "<subscription_add_on>" + node.OuterXml.Substring(sIndex, (eIndex - sIndex)) + "<quantity>1</quantity>" + " </subscription_add_on>";
            sb.Append(subs);
        }
 sb.Append("</subscription");

上面的代码片段总是取出第一个子字符串,对我来说它看起来非常低效。

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

谢谢!

c# string asp.net-core stringbuilder c#-7.0
1个回答
1
投票

只需解析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
        )
    )
);
© www.soinside.com 2019 - 2024. All rights reserved.