英文:
How to return image data of an xml file with java
问题
以下是翻译好的部分:
public String image(){
{
try {
builder = factory.newDocumentBuilder();
Document doc = builder.parse(filename);
NodeList messageList = doc.getElementsByTagName("picture");
for(int i=0; i<messageList.getLength(); i++){
Node node = messageList.item(i);
if(node.getNodeType() == Node.ELEMENT_NODE){
Element element = (Element) node;
System.out.println(element.getTextContent());
}
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return "error";
}
这是一个示例的 XML 文件:
<?xml version="1.0" encoding="UTF-8"?>
<test>
<text>无法获取工作的图片标签 zzz</text>
<picture data="iVBORw0KGgoAAAANSUhEUgAAKXRFWHRDcAAHdElNRQfk6CIIiPoZwD+ALXGFxj6BgYeU7BO4tToSDFHYWZ2+/c03OzPZDRJNYcgVwG4hZQOLPeF24ZkCe6ZxDCOqHcmxmsr+hsicahss+n8vYb8NHZPTJxi/RGC5IqbRwqH6uxVTX+5LvHtvT/V/R6PGh/iF4GHoBAwz7RD26spwq6Amh/AAAAAElFTkSuQmCC" />
</test>
英文:
Hi I'm using dom to parse xml files mostly through the use of getTextContent, but for some reason I can't get the text from the picture tag and I'm not sure why
public String image(){
{
try {
builder = factory.newDocumentBuilder();
Document doc= builder.parse(filename);
NodeList messageList=doc.getElementsByTagName("picture");
for(int i=0;i<messageList.getLength();i++){
Node node=messageList.item(i);
if(node.getNodeType()==Node.ELEMENT_NODE){
Element element=(Element) node;
System.out.println(element.getTextContent());
}
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return "error";
}
this is an example xml file
<?xml version="1.0" encoding="UTF-8"?>
<test>
<text>can't get picture tag to work zzz</text>
<picture data="iVBORw0KGgoAAAANSUhEUgAAKXRFWHRDcAAHdElNRQfk6CIIiPoZwD+ALXGFxj6BgYeU7BO4tToSDFHYWZ2+/c03OzPZDRJNYcgVwG4hZQOLPeF24ZkCe6ZxDCOqHcmxmsr+hsicahss+n8vYb8NHZPTJxi/RGC5IqbRwqH6uxVTX+5LvHtvT/V/R6PGh/iF4GHoBAwz7RD26spwq6Amh/AAAAAElFTkSuQmCC" />
</test>
</details>
# 答案1
**得分**: 1
因为您正在尝试获取空标签的内容。您想要的是 `data` 属性的值,可以按以下方式获取:
```java
element.getAttributes().getNamedItem("data").getNodeValue()
英文:
That's because you are trying to get content of the empty tag. What you want is the value of the data
attribute, which can be obtained as follows:
element.getAttributes().getNamedItem("data").getNodeValue()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论