我必须解析给定的 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>
我的问题是我必须在 html 中找到“@MarcoS 有一个很好的解决方案,它使用 NodeTraversor 在https://stackoverflow.com/a/6594828/1861357和我只做一个要更改的节点列表”并放一个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 解析器都可以做到这一点?