나는 장난 삼아 놀고있다. DOM 구조에서 특정 노드를 감지하고 노드 주변에서 텍스트 데이터를 추출하는 것을 포함하는 무언가를 작성하려고합니다. 예 : 부모 노드의 텍스트, 형제 노드 등. 몇 가지 예를 연구하고 읽은 다음 이미지 노드에 대해이 작업을 수행하는 플러그인을 작성하려고했습니다. 코드의 일부노드의 주변 텍스트를 얻는 방법?
if("img".equalsIgnoreCase(nodeName) && nodeType == Node.ELEMENT_NODE){
String imageUrl = "No Url";
String altText = "No Text";
String imageName = "No Image Name"; //For the sake of simpler code, default values set to
//avoid nullpointerException in findMatches method
NamedNodeMap attributes = currentNode.getAttributes();
List<String>ParentNodesText = new ArrayList<String>();
ParentNodesText = getSurroundingText(currentNode);
//Analyze the attributes values inside the img node. <img src="xxx" alt="myPic">
for(int i = 0; i < attributes.getLength(); i++){
Attr attr = (Attr)attributes.item(i);
if("src".equalsIgnoreCase(attr.getName())){
imageUrl = getImageUrl(base, attr);
imageName = getImageName(imageUrl);
}
else if("alt".equalsIgnoreCase(attr.getName())){
altText = attr.getValue().toLowerCase();
}
}
private List<String> getSurroundingText(Node currentNode){
List<String> SurroundingText = new ArrayList<String>();
while(currentNode != null){
if(currentNode.getNodeType() == Node.TEXT_NODE){
String text = currentNode.getNodeValue().trim();
SurroundingText.add(text.toLowerCase());
}
if(currentNode.getPreviousSibling() != null && currentNode.getPreviousSibling().getNodeType() == Node.TEXT_NODE){
String text = currentNode.getPreviousSibling().getNodeValue().trim();
SurroundingText.add(text.toLowerCase());
}
currentNode = currentNode.getParentNode();
}
return SurroundingText;
}
이것은 제대로 작동하지 않는 것 같습니다. img 태그가 감지되면 이미지 이름과 URL이 검색되지만 더 이상 도움이되지 않습니다. getSurroundingText 모듈이 너무 못 생겨서 시도했지만 개선하지 못했습니다. 이미지와 관련이있는 텍스트를 어디서 어떻게 추출 할 수 있을지는 명확하지 않습니다. 어떤 도움을 주시겠습니까?