gpt4 book ai didi

java - 如何修改代码,使其也与带有属性的 html 标签相匹配?

转载 作者:行者123 更新时间:2023-11-30 06:21:58 24 4
gpt4 key购买 nike

这就是我用来匹配 HTML 标签的代码;当我使用诸如 <body> </body> 之类的标签时它会起作用但不包括 <table border = "3"> </table> 。如何修改它以便它也可以与属性一起使用?部分代码如下:

public class MatchDel {
public static boolean isHTMLMatched(String html) {
LinkedStack<String> buffer = new LinkedStack<>();
int j = html.indexOf('<');
while(j != -1) {
int k = html.indexOf('>', j+1);
if(k == -1) {
return false;
}
String tag = html.substring(j+1, k);
if(!tag.startsWith("/")) {
buffer.push(tag);
}
else {
if(buffer.isEmpty()) {
return false;
}
if(!tag.substring(1).equals(buffer.pop())) {
return false;
}
}
j = html.indexOf('<', k+1);
}
return buffer.isEmpty();
}

public static void main(String[] args) {
System.out.println(isHTMLMatched("<body> </body>"));
}
}

最佳答案

您可以解析文档,以查找某些元素并获取这些元素内的数据。

要获取属性的值,请使用 Node.attr(String key) 方法对于元素(及其组合子元素)上的文本,请使用 Element.text()对于 HTML,根据需要使用 Element.html()Node.outerHtml()

例如:

    String html = "<p>An <a href='http://example.com/'><b>example</b></a> link.</p>";
Document doc = Jsoup.parse(html);
Element link = doc.select("a").first();

String text = doc.body().text(); // "An example link"
String linkHref = link.attr("href"); // "http://example.com/"
String linkText = link.text(); // "example""

String linkOuterH = link.outerHtml();
// "<a href="http://example.com"><b>example</b></a>"
String linkInnerH = link.html(); // "<b>example</b>"

参见jsoup: Java HTML Parser

<小时/>

编辑:

代码中的问题出在这一行: if(!tag.substring(1).equals(buffer.pop())) ,因为您正在比较 table border = "3" 到字符串 table 中,您可以通过仅取字符串 table border = "3"中的第一个单词 table 来解决此问题,你可以试试这个代码:

public class d {
public static boolean isHTMLMatched(String html) {
Stack<String> buffer = new Stack<>();
String st="";//ADDED BY ME
String s="";//ADDED BY ME
int j = html.indexOf('<');
while(j != -1) {
int k = html.indexOf('>', j+1);
if(k == -1) {
return false;
}
String tag = html.substring(j+1, k);
if(!tag.startsWith("/")) {
buffer.push(tag);
}
else {
if(buffer.isEmpty()) {
return false;
}
s=buffer.pop();//ADDED BY ME
if(s.indexOf(" ")!=-1)//ADDED BY ME
st=s.substring(0, s.indexOf(" "));//ADDED BY ME
else st=s;//ADDED BY ME
if(!tag.substring(1).equals(st)) {//<----------------PROBLEM WAS HERE
return false;
}
}
j = html.indexOf('<', k+1);
}
return buffer.isEmpty();
}

public static void main(String[] args) {
System.out.println(isHTMLMatched("<table border = \"3\"> </table>"));
}
}

关于java - 如何修改代码,使其也与带有属性的 html 标签相匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47947684/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com