gpt4 book ai didi

java - 使用Java解析xml

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

我正在尝试解析 dom 元素。

元素元素:

<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<id>http://X/feed2</id>
<title>Sample Feed</title>
<entry>
<id>http://X/feed2/104</id>
<title>New Title</title>
</entry>
</feed>

我正在尝试获取以下条目:

<entry>
<id>http://top.cs.vt.edu/libx2/vsony7@vt.edu/feed2/104</id>
<title>New Title</title>
</entry>

我正在使用 xpath 解析 xml:

"/atom:feed/atom:entry[atom:id=\"http://X/feed2/104\"]"

但是,当我尝试解析 Dom Element 时遇到异常。有人可以建议一种简单的方法来在 Java 中实现此目的吗?

请查看我的完整代码:

public static parseXml() {
String externalEntryIdUrl = "http://theta.cs.vt.edu/~rupen/thirtylibapps/137";
String externalFeedUrl = StringUtils.substringBeforeLast(externalEntryIdUrl, "/");
try {
URL url = new URL(externalFeedUrl);
InputStream externalXml = new BufferedInputStream(url.openStream());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(externalXml);
Element externalFeed = doc.getDocumentElement();
String atomNameSpace = "xmlns:atom=\"http://www.w3.org/2005/Atom\"";
String entryIdPath = String.format("//%s:entry[%s:id=%s]", atomNameSpace, atomNameSpace, externalEntryIdUrl);
Element externalEntry = (Element) XPathSupport.evalNode(entryIdPath, externalFeed);
} catch (Exception ex) {
// Throw exception
}
}

static synchronized Node evalNode(String xpathExpr, Node node) {
NodeList result = evalNodeSet(xpathExpr, node);
if (result.getLength() > 1)
throw new Error ("More than one node for:" + xpathExpr);
else if (result.getLength() == 1)
return result.item(0);
else
return null;
}

static synchronized NodeList evalNodeSet(String xpathExpr, Node node) {
try {
static XPath xpath = factory.newXPath();
xpath.setNamespaceContext(context);

static NamespaceContext context = new NamespaceContext() {
private Map<String, String> prefix2URI = new HashMap<String, String>();
{
prefix2URI.put("libx", "http://libx.org/xml/libx2");
prefix2URI.put("atom", "http://www.w3.org/2005/Atom");
}
};

XPathExpression expr = xpath.compile(xpathExpr);
Object result = expr.evaluate(node, XPathConstants.NODESET);
return (NodeList)result;
} catch (XPathExpressionException xpee) {
throw new Error ("An xpath expression exception: " + xpee);
}
}

严重:>>java.lang.Error:xpath 表达式异常:javax.xml.xpath.XPathExpressionException

最佳答案

您可以使用 SAX 解析器。这是 SAX 解析的示例 http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/

关于java - 使用Java解析xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9059851/

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