Java org.w3c.dom:仅获取当前节点的标记值
我正在用Java解析以下形式的XML文档Java org.w3c.dom:仅获取当前节点的标记值,java,xml,dom,xml-parsing,Java,Xml,Dom,Xml Parsing,我正在用Java解析以下形式的XML文档 <Fields> <Field> <Key>Name</Key> <Length>20</Length> <-- what if this is missing? <Subfields> <Field> <Key>First
<Fields>
<Field>
<Key>Name</Key>
<Length>20</Length> <-- what if this is missing?
<Subfields>
<Field>
<Key>First Name</Key> <-- takes this as the first item
<Length>11</Length>
</Field>
<Field>
<Key>Second Name</Key>
<Length>9</Length>
</Field>
</Subfields>
</Field>
...
</Fields>
方法getElementsByTagName
返回所有子体的长度列表,因此第一项是主字段的长度
当主字段不包含长度时,问题就会出现。在这种情况下,上面的表达式给出了第一个子节点的长度。是否有任何方法仅获取当前节点的标记值,如果没有,只需返回NULL
编辑:
我找到的一种方法是检查该项是否是当前字段的直接子项。这似乎很有效
element==(Element)attribs.getParentNode()
但我相信有一种更好的方法可以做到这一点。如果您只想获取节点的直接子节点,您可以这样做:
Node attribs = (Node)element.getElementsByTagName("Field").item(0);
Node childNode = attribs.getFirstChild(); // returns Key node
while( childNode.getNextSibling()!=null ){
childNode = childNode.getNextSibling();// returns all siblings of Key node
if (childNode.getNodeType() == Node.ELEMENT_NODE) {
Element childElement = (Element) childNode;
这将返回字段的第一个子项
,并迭代其同级项
Node attribs = (Node)element.getElementsByTagName("Field").item(0);
Node childNode = attribs.getFirstChild(); // returns Key node
while( childNode.getNextSibling()!=null ){
childNode = childNode.getNextSibling();// returns all siblings of Key node
if (childNode.getNodeType() == Node.ELEMENT_NODE) {
Element childElement = (Element) childNode;