按名称仅获取 XML 直接子元素
我的问题是:当存在与父元素的孙子"同名的其他元素时,如何直接获取特定父元素下的元素.
My question is: How can I get elements directly under a specific parent element when there are other elements with the same name as a "grandchild" of the parent element.
我正在使用 Java DOM 库 解析 XML 元素 和我'我遇到了麻烦.这是我正在使用的 一些(一小部分)xml:
I'm using the Java DOM library to parse XML Elements and I'm running into trouble. Here's some (a small portion) of the xml I'm using:
<notifications>
<notification>
<groups>
<group name="zip-group.zip" zip="true">
<file location="C:validdirectory" />
<file location="C:anothervalidfile.doc" />
<file location="C:validfilehere.txt" />
</group>
</groups>
<file location="C:validfile.txt" />
<file location="C:validfile.xml" />
<file location="C:validfile.doc" />
</notification>
</notifications>
如您所见,您可以在两个地方放置 <file>
元素.无论是在组内还是在组外.我真的希望它采用这种结构,因为它对用户更友好.
As you can see, there are two places you can place the <file>
element. Either in groups or outside groups. I really want it structured this way because it's more user-friendly.
现在,每当我调用 notificationElement.getElementsByTagName("file");
时,它都会为我提供所有 <file>
元素,包括 < 下的元素;group>
元素.我以不同的方式处理这些文件中的每一种,所以这个功能是不可取的.
Now, whenever I call notificationElement.getElementsByTagName("file");
it gives me all the <file>
elements, including those under the <group>
element. I handle each of these kinds of files differently, so this functionality is not desirable.
我想到了两种解决方案:
I've thought of two solutions:
- 获取文件元素的父元素并进行相应处理(取决于是
还是
. - 重命名第二个
<file>
元素以避免混淆.
- Get the parent element of the file element and deal with it accordingly (depending on whether it's
<notification>
or<group>
. - Rename the second
<file>
element to avoid confusion.
这些解决方案都不像只是让事情保持原样并只获得 <file>
元素,这些元素是 <notification>
的直接子元素元素.
Neither of those solutions are as desirable as just leaving things the way they are and getting only the <file>
elements which are direct children of <notification>
elements.
我愿意接受 IMPO 关于最佳"方法的评论和回答,但我对 DOM 解决方案真的很感兴趣,因为这就是其余的这个项目正在使用.谢谢.
I'm open to IMPO comments and answers about the "best" way to do this, but I'm really interested in DOM solutions because that's what the rest of this project is using. Thanks.
推荐答案
嗯,这个问题的 DOM 解决方案其实很简单,虽然不太优雅.
Well, the DOM solution to this question is actually pretty simple, even if it's not too elegant.
当我遍历调用notificationElement.getElementsByTagName("file")
时返回的filesNodeList
时,我只检查父节点的名称是否为通知"".如果不是,那么我将忽略它,因为这将由 <group>
元素处理.这是我的代码解决方案:
When I iterate through the filesNodeList
, which is returned when I call notificationElement.getElementsByTagName("file")
, I just check whether the parent node's name is "notification". If it isn't then I ignore it because that will be handled by the <group>
element. Here's my code solution:
for (int j = 0; j < filesNodeList.getLength(); j++) {
Element fileElement = (Element) filesNodeList.item(j);
if (!fileElement.getParentNode().getNodeName().equals("notification")) {
continue;
}
...
}
相关文章