加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在xml标记中包装一些文本的最佳方法是什么?

发布时间:2020-12-16 01:36:26 所属栏目:百科 来源:网络整理
导读:我试图在C#中使用 Regex来匹配xml文档中的一个部分并将该部分包装在一个标记内. 例如,我有这个部分: intro pthis is the first section of content/p p this is another/p/intro 我希望它看起来像这样: intro bodyText p this is asdf/p p yada yada /p /b
我试图在C#中使用 Regex来匹配xml文档中的一个部分并将该部分包装在一个标记内.

例如,我有这个部分:

<intro>
    <p>this is the first section of content</p>
    <p> this is another</p>
</intro>

我希望它看起来像这样:

<intro>
   <bodyText>
      <p> this is asdf</p>
      <p> yada yada </p>
   </bodyText>
</intro>

有什么想法吗?

我正在考虑在C#中使用XPath类,或者只是通过阅读文档并使用Regex.我无论如何都无法弄明白.

这是一次尝试:

StreamReader reader = new StreamReader(filePath);
        string content = reader.ReadToEnd();
        reader.Close();

        /* The regex stuff would go here */

        StreamWriter writer = new StreamWriter(filePath);
        writer.Write(content);
        writer.Close();
    }

谢谢!

解决方法

我不建议为此任务使用正则表达式.相反,您可以使用LINQ to XML来完成它.例如,以下是如何在新标记中包含一些标记:

XDocument doc = XDocument.Load("input.xml");
var section = doc.Root.Elements("p");
doc.Root.ReplaceAll(new XElement("bodyText",section));
Console.WriteLine(doc.ToString());

结果:

<intro>
  <bodyText>
    <p>this is the first section of content</p>
    <p> this is another</p>
  </bodyText>
</intro>

我假设您的实际文档与您发布的示例有很大不同,因此代码需要进行一些调整以满足您的要求,但如果您阅读XDocument的文档,您应该能够做到您想要的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读