繁体   English   中英

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

[英]What is the best way to wrap some text in an xml tag?

我试图在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的文档,您应该能够做您想要的。

我建议使用System.XML和XPath - 我不认为XML被认为是类似于HTML的常规语言,在尝试使用正则表达式解析时会导致问题。

使用类似的东西

XMLDocument doc = new XMLDocument();
doc.Load("Path to your xml document");

请享用!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM