使用 Java 和 Xerces 访问内部 XML 数据
我正在尝试使用 Xerces 解析 XML 文档,但我似乎无法访问元素内的数据,下面是一个示例 XML 文档;
<sample>
<block>
<name>tom</name>
<age>44</age>
<car>BMW</car>
</block>
<block>
<name>Jenny</name>
<age>23</age>
<car>Ford</car>
</block>
</sample>
到目前为止,我能产生的唯一输出是;
Sample
block
name
age
car
block
name
age
car
这只是节点名称的列表。我尝试过node.getValue(),但这只是返回null,所以我猜那是错误的!
如何访问里面的数据?这是到目前为止的基础知识;
public static void display(String file) {
try{
DOMParser parser = new DOMParser();
parser.parse(file);
Document doc = parser.getDocument();
read(doc);
}
catch(Exception e){e.printStackTrace(System.err);}
}
public static void read(Node node) {
if(node == null) {return;}
int type = node.getNodeType();
//System.out.print((node));
switch (type) {
case Node.DOCUMENT_NODE: {
display_all(((Document)node).getDocumentElement());
break;
}
case Node.TEXT_NODE:
break;
case Node.ELEMENT_NODE: {
System.out.println(node.getNodeName());
NodeList child = node.getChildNodes();
if(child != null) {
int length = child.getLength();
for (int i = 0; i < length ; i++) {
display_all(child.item(i));
}
}
break;
}
}
}
I am trying to parse a XML document using Xerces, but I cant seem to access the data within the elements, below is a sample XML document;
<sample>
<block>
<name>tom</name>
<age>44</age>
<car>BMW</car>
</block>
<block>
<name>Jenny</name>
<age>23</age>
<car>Ford</car>
</block>
</sample>
SO far the only output I can produce is;
Sample
block
name
age
car
block
name
age
car
Which is just a list of the node names. I have tried node.getValue(), but this just returns null, so im guessing thats wrong!
How can I access the data inside? Here is what is the basics so far;
public static void display(String file) {
try{
DOMParser parser = new DOMParser();
parser.parse(file);
Document doc = parser.getDocument();
read(doc);
}
catch(Exception e){e.printStackTrace(System.err);}
}
public static void read(Node node) {
if(node == null) {return;}
int type = node.getNodeType();
//System.out.print((node));
switch (type) {
case Node.DOCUMENT_NODE: {
display_all(((Document)node).getDocumentElement());
break;
}
case Node.TEXT_NODE:
break;
case Node.ELEMENT_NODE: {
System.out.println(node.getNodeName());
NodeList child = node.getChildNodes();
if(child != null) {
int length = child.getLength();
for (int i = 0; i < length ; i++) {
display_all(child.item(i));
}
}
break;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
getNodeValue()
返回您当前跳过的文本节点的值。我认为您可能会感到困惑的是 XML 的实际结构以及此类内容的子级是什么:
上面的代码片段可能有助于解释。
这也是为什么 dom4j、JAXB、XPath 等使事情变得更加容易的原因。
getNodeValue()
returns the value of a text node, which you currently skip over.I think where you might be getting confused is how XML is actually structured, and what the children of something like this is:
The above code snippet may help explain.
It's also why things like dom4j, JAXB, XPath, etc. make things much easier.