[英]Parsing xml using Java
我正在尝试解析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/的示例
您可以利用NamespaceContext
并执行以下操作:
package forum9059851;
import java.io.FileInputStream;
import java.util.Iterator;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.*;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
public class Demo {
public static void main(String[] args) {
try {
XPathFactory xpf = XPathFactory.newInstance();
XPath xp = xpf.newXPath();
xp.setNamespaceContext(new MyNamespaceContext());
XPathExpression xpe = xp.compile("ns:feed/ns:entry");
FileInputStream xmlStream = new FileInputStream("src/forum9059851/input.xml");
InputSource xmlInput = new InputSource(xmlStream);
Element result = (Element) xpe.evaluate(xmlInput, XPathConstants.NODE);
System.out.println(result);
} catch (Exception ex) {
// Throw exception
}
}
private static class MyNamespaceContext implements NamespaceContext {
public String getNamespaceURI(String prefix) {
if("ns".equals(prefix)) {
return "http://www.w3.org/2005/Atom";
}
return null;
}
public String getPrefix(String namespaceURI) {
return null;
}
public Iterator getPrefixes(String namespaceURI) {
return null;
}
}
}
如果您不想重新发明轮子并想解析提要数据,我建议您使用已经可用的Rome库。
我发现从URL提取xml时没有设置名称空间意识。
所以,
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
这样做可以解决我的问题。 如果不这样做,那么如我的示例所示,在解析xml时为XPathFactory实例设置名称空间上下文将无法正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.