通过 XML 中的特定标记名称查找元素是否存在

发布于 2024-09-08 07:27:51 字数 1300 浏览 4 评论 0原文

我有一个 XML 文件,其中一些子标签(子节点元素)是可选的。 例如,

<part>
   <note>
       </rest>
   </note>

   <note>
       <pitch></pitch>
   </note>

   <note>
       <pitch></pitch>
   </note>
</part>

但是当我按标签读取 XML 文件时,它会抛出 NullPointerException - 因为某些子标签是可选的(例如上面示例中的休息和俯仰)。我怎样才能过滤掉这个?我找不到任何方法来查找特定标签名称是否存在元素。即使我有一个条件来检查 getElementsByTagName("tag-name") 方法是否不返回 NULL - 它仍然进入条件主体并显然抛出异常。 我该如何解决这个问题?

java代码是:

if(fstelm_Note.getElementsByTagName("rest")!=null){
    if(fstelm_Note.getElementsByTagName("rest")==null){
        break;
    }
    NodeList restElmLst = fstelm_Note.getElementsByTagName("rest");
    Element restElm = (Element)restElmLst.item(0);
    NodeList rest = restElm.getChildNodes();

    String restVal = ((Node)rest.item(0)).getNodeValue().toString();

}else if(fstelm_Note.getElementsByTagName("note")!=null){
    if(fstelm_Note.getElementsByTagName("note")==null){
        break;
    }

    NodeList noteElmLst = fstelm_Note.getElementsByTagName("note");
    Element noteElm = (Element)noteElmLst.item(0);

    NodeList note = noteElm.getChildNodes();
    String noteVal = ((Node)note.item(0)).getNodeValue().toString();
}

任何见解或建议表示赞赏。 提前致谢。

I have an XML file where some sub tags (child node elements) are optional.
e.g.

<part>
   <note>
       </rest>
   </note>

   <note>
       <pitch></pitch>
   </note>

   <note>
       <pitch></pitch>
   </note>
</part>

But when I read the XML files by tags, it throws a NullPointerException - since some sub-tags are optional (e.g. rest and pitch in above example). How can I filter this out? I couldn't come across any methods to find whether an element exists by a particular tag name. Even if I have a condition to check whether getElementsByTagName("tag-name") method not returns NULL - still it goes in the condition body and obviously throw the exception.
How may I resolve this?

The java code is:

if(fstelm_Note.getElementsByTagName("rest")!=null){
    if(fstelm_Note.getElementsByTagName("rest")==null){
        break;
    }
    NodeList restElmLst = fstelm_Note.getElementsByTagName("rest");
    Element restElm = (Element)restElmLst.item(0);
    NodeList rest = restElm.getChildNodes();

    String restVal = ((Node)rest.item(0)).getNodeValue().toString();

}else if(fstelm_Note.getElementsByTagName("note")!=null){
    if(fstelm_Note.getElementsByTagName("note")==null){
        break;
    }

    NodeList noteElmLst = fstelm_Note.getElementsByTagName("note");
    Element noteElm = (Element)noteElmLst.item(0);

    NodeList note = noteElm.getChildNodes();
    String noteVal = ((Node)note.item(0)).getNodeValue().toString();
}

Any insight or suggestions are appreciated.
Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

只是在用心讲痛 2024-09-15 07:27:51

我遇到了同样的问题(使用 getElementsByTagName() 获取 XML 文件中的“可选”节点),因此我可以根据经验告诉如何解决它。事实证明,当没有找到匹配的节点时,getElementsByTagName不会返回null;相反,它返回一个长度为零的 NodeList 对象。

您可能会猜到,在尝试获取 XML 文件内容之前检查节点是否存在于 XML 文件中的正确方法类似于:

NodeList nl = element.getElementsByTagName("myTag");
if (nl.getLength() > 0) {
    value = nl.item(0).getTextContent();
}

确保指定“默认”值,以防从未找到标记。

I had this very same problem (using getElementsByTagName() to get "optional" nodes in an XML file), so I can tell by experience how to solve it. It turns out that getElementsByTagName does not return null when no matching nodes are found; instead, it returns a NodeList object of zero length.

As you may guess, the right way to check if a node exists in an XML file before trying to fetch its contents would be something similar to:

NodeList nl = element.getElementsByTagName("myTag");
if (nl.getLength() > 0) {
    value = nl.item(0).getTextContent();
}

Make sure to specify a "default" value in case the tag is never found.

仙气飘飘 2024-09-15 07:27:51

您的 NodeList 可能不为 null,而是为空。您可以尝试像这样更改代码并看看会发生什么吗?

NodeList restElmLst = fstelm_Note.getElementsByTagName("rest");
if (restElmLst != null && !restElmLst.isEmpty())
{
    Element restElm = (Element)rests.item(0);
...

等等(双重检查语法等,因为我不在编译器前面。)

It may be that your NodeLists are not null, but are empty. Can you try changing your code like this and see what happens?

NodeList restElmLst = fstelm_Note.getElementsByTagName("rest");
if (restElmLst != null && !restElmLst.isEmpty())
{
    Element restElm = (Element)rests.item(0);
...

etc. (Doublecheck syntax etc., since I'm not in front of a compiler.)

软糖 2024-09-15 07:27:51

您的要求非常不清楚,但我很可能使用javax.xml.xpath 包使用 XML 路径语言 (XPath)

看一下:

但你应该尝试解释一下您试图解决的一般问题,而不是您面临的具体问题。但这样做,1.您可能会得到更好的答案,2.当前选择的路径可能不是最好的。

Your requirements are extremely unclear but I would very likely use the javax.xml.xpath package to parse your XML document with the XML Path Language (XPath).

Have a look at:

But you should try to explain the general problem you are trying to solve rather than the specific problem you're facing. But doing so, 1. you will probably get better answers and 2. the current chosen path might not be the best one.

2024-09-15 07:27:51

尝试如下所示

bool hasCity = OrderXml.Elements("City").Any();

,其中 OrderXml 是父元素。

Try something like below

bool hasCity = OrderXml.Elements("City").Any();

where OrderXml is parent element.

故人如初 2024-09-15 07:27:51

首先需要创建nodelist,然后检查nodelist的长度以检查当前元素是否存在于xml字符串中。

NodeList restElmLst = fstelm_Note.getElementsByTagName("rest");

if (restElmLst.getLength() > 0) {
    String restVal = restElm.getElementsByTagName("rest").item(0).getTextContent(); 
}                               

First you need to create the nodelist and then check the length of nodelist to check whether the current element exists or not in the xml string.

NodeList restElmLst = fstelm_Note.getElementsByTagName("rest");

if (restElmLst.getLength() > 0) {
    String restVal = restElm.getElementsByTagName("rest").item(0).getTextContent(); 
}                               
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文