简体   繁体   English

使用Jsoup时如何获取元素的LineNumber?

[英]How can I get the LineNumber of the element when using Jsoup?

such as: 如:

Document doc = Jsoup.parse(file,"UTF-8");

Elements eles = doc.getElementsByTag("style");

How can I get the lineNumber of eles[0] in the file? 如何获取文件中eles[0]的lineNumber?

There is no way for you to do it with Jsoup API. 您无法通过Jsoup API做到这一点。 I have checked on their source code: org.jsoup.parser.Parser maintains no position information of the element in the original input. 我检查了它们的源代码: org.jsoup.parser.Parser在原始输入中不保留元素的位置信息。

Please, refer to sources on Grep Code 请参考Grep代码的来源

Provided that Jsoup is build for extracting and manipulating data I don't believe that they will have such feature in future as it is ambigous what element position is after manipulation and costly to maintain actual references. 如果Jsoup是为提取和处理数据而构建的,我不相信它们将来会具有这样的功能,因为操作后元素位置不明确,维护实际引用的成本很高。

There is no direct way. 没有直接的方法。 But there is an indirect way. 但是有一种间接的方式。 Once you find the point of interest like an attribute, simply add a token as html before the element, and write the file to another temporary file. 找到兴趣点(如属性)后,只需在元素之前添加标记(如html),然后将文件写入另一个临时文件即可。 The next step is do a search for the token, using text editing tools. 下一步是使用文本编辑工具搜索令牌。

code is as follows. 代码如下。

Step-1: 第1步:

// get an element //获取一个元素
for (Element element : doc.getAllElements()) { 对于(Element element:doc.getAllElements()){
... some code to get attributes of element ... ...一些代码来获取元素的属性...

String myAttr = attribute.getKey(); 字符串myAttr = attribute.getKey();
if (myAttr.equals(" some-attribute-name-of-interest ") { 如果(myAttr.equals(“ 感兴趣的某些属性名称 ”){
System.out.println(attribute.getKey() + "::" + attribute.getValue()); System.out.println(attribute.getKey()+“ ::” + attribute.getValue());
element.before("<!-- My Special Token : ABCDEFG -->"); element.before(“ <!-我的特殊令牌:ABCDEFG->”);
} }

Step-2: 第2步:

// write the doc back to a temporary file //将文档写回到临时文件
// see: How to save a jsoup document as text file //请参阅: 如何将jsoup文档另存为文本文件

Step-3: 步骤3:

The last step is search for "My Special Token : ABCDEFG" in the output file using a text editing tool. 最后一步是使用文本编辑工具在输出文件中搜索“我的特殊令牌:ABCDEFG”。

jsoup is a nice library. jsoup是一个不错的库。 I thought this would help others. 我以为这会帮助别人。

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

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