gpt4 book ai didi

Java:解析 XML 数据的函数 - 没有输出任何内容

转载 作者:行者123 更新时间:2023-12-01 12:42:05 25 4
gpt4 key购买 nike

我对使用 Java 进行 XML 处理还比较陌生,所以预计会出现一些错误,但无论如何......我正在尝试解析以下 XML 数据:

<强> http://msdn.microsoft.com/en-us/library/ms762271(v=vs.85).aspx

我想使用一个函数来完成此操作,其中 XML 标记的名称和 NodeList 作为参数传入,并返回内容。

谢谢。

import java.io.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

public class Files {

@SuppressWarnings("unused")

public static void main (String [] args) throws IOException, ParserConfigurationException, SAXException{

String address = "/home/leo/workspace/Test/Files/src/file.xml";

String author = "author";
String title = "title";
String genre = "genre";
String price = "price";
String publish = "publish_date";
String descr = "description";


File xmlFile = new File(address);

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = factory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);

doc.getDocumentElement().normalize();

System.out.println(doc.getDocumentElement().getNodeName());
NodeList n = doc.getElementsByTagName("book");
System.out.println("Number of books " + n.getLength());

getElement(author, n);

}

private static void getElement(String elementName, NodeList n){

for (int i = 0; i < n.getLength(); i++){
Node showNode = n.item(i);

Element showElement = (Element)showNode;

System.out.println(elementName + ": " +
showElement.getAttribute(elementName)

);

}

}

}

最佳答案

问题是:showElement.getAttribute(elementName)

你想要获取一个节点的值,但是getAttribute是获取节点的属性,你应该弄清楚属性在XML中的含义。

你可以这样获取值:

private static void getElement(String elementName, NodeList n){

for (int i = 0; i < n.getLength(); i++){
Node showNode = n.item(i);

NodeList nl = showNode.getChildNodes();
for(int j=0;j<nl.getLength();j++)
{
Node nd=nl.item(j);
if(nd.getNodeName().equals(elementName))
{
System.out.println(elementName + ":" + nd.getTextContent());
}
}
}
}

}

关于Java:解析 XML 数据的函数 - 没有输出任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25005654/

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