【问题标题】:Scanning for a XML tag and copying the whole content into another file till end tag is encountered扫描 XML 标记并将整个内容复制到另一个文件中,直到遇到结束标记
【发布时间】:2021-02-25 10:20:34
【问题描述】:

我有一个日志文件,其中包含文本日志以及 xml 消息。该函数应检查特定的 xml 标记。一旦遇到它应该复制该 xml 消息的所有内容,直到遇到结束标记到另一个文件中。 考虑以下xml

<?xml version="1.0"?>
obo.adapter :         Started processing the message
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
</catalog>
obo.crdadapter. :         stopped processing the message

要扫描的标签是“目录”,所以输出应该是

<catalog>
     <book id="bk101">
          <author>Gambardella, Matthew</author>
          <title>XML Developer's Guide</title>
          <genre>Computer</genre>
          <price>44.95</price>
          <publish_date>2000-10-01</publish_date>
          <description>An in-depth look at creating applications 
          with XML.</description>
       </book>
 </catalog>

简单的方法是做

BufferedReader in = new BufferedReader(new FileReader("/app/log/log.txt"));
String line;
while((line = in.readLine()) != null)
{
   if(line.equalIgnoreCase("<tagName>")){
    //logic here
   }
}
in.close();

但是有没有更好的方法来实现这一点?请注意 xml 正文可能会更改,因此我无法创建它的 pojo。

【问题讨论】:

    标签: java xml spring


    【解决方案1】:

    我能够使用正则表达式模式匹配来做到这一点。首先将文件加载到 stringBuilder 中,然后对其进行模式匹配。它适用于最大 72MB 的文件

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-21
      相关资源
      最近更新 更多