我必须解析给定的HTML并修改其内容并保存修改后的版本。
我的HTML输入:
<div>
<div class="post-text"><p>@MarcoS had an excellent solution using a NodeTraversor to make a list of nodes to change at <a href="https://stackoverflow.com/a/6594828/1861357">https://stackoverflow.com/a/6594828/1861357</a> and I only very slightly modified his method which replaces a node (a set of tags) with the data in the node plus whatever information you would like to add.</p>
<p>To store a String in memory I used a static <code>StringBuilder</code> to save the HTML in memory. </p>
<p>First we read in the HTML file (that is manually specified, this can be changed), then we make a series of checks to change whatever nodes with any data that we want.</p>
<p>The one problem that I didn't fix in the solution by MarcoS was that it split each individual word, instead of looking at a line. However I just used '-' for multiple words, because otherwise it places the string directly after that word.</p>
<p>So a full implementation: </p>
</div>
<div>
<div class="post-text" itemprop="description">
<p>Recently I was recommended to use JSoup to parse and modify HTML documents. </p>
<p>However what if I have a HTML document that I want to modify (to send, store somewhere else, etc.), how might I go about doing that without changing the original document? </p>
</div>
我的问题是我必须找到“@MarcoS有一个很好的解决方案,使用NodeTraversor来制作要在https://stackoverflow.com/a/6594828/1861357更改的节点列表,我只在html中添加div tag
(或其周围的任何东西(不在它的父标签或整个段落)。
我搜索的文本之间会有html标签。
我希望输出如下:
<div class="post-text"><p><div id="myDiv">@MarcoS had an excellent solution using a NodeTraversor to make a list of nodes to change at <a href="https://stackoverflow.com/a/6594828/1861357">https://stackoverflow.com/a/6594828/1861357</a> and I only</div>......</div>
RegEx是唯一的解决方案,还是任何HTML Parser都可以做到这一点?
答案 0 :(得分:1)
如果您不想使用某些XML解析器,可以尝试使用regexp:
String xmlStr = "some_xml";
xmlStr = xml.replaceAll(">\\s+<", "><").trim();