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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3202052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:21:23  来源:igfitidea点击:

find whether an element exists by a particular tag name in XML

javaxmloptionaltagname

提问by Dolphin

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

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

<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?

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

The java code is:

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();
}

Any insight or suggestions are appreciated. Thanks in advance.

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

回答by jwismar

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

可能是您的 NodeLists 不是空的,而是空的。你能试着像这样改变你的代码,看看会发生什么吗?

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.)

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

回答by Pascal Thivent

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

您的要求非常不清楚,但我很可能会使用该javax.xml.xpath包来使用XML 路径语言 (XPath)解析您的 XML 文档。

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.

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

回答by DanyAlejandro

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 nullwhen no matching nodes are found; instead, it returns a NodeList object of zero length.

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

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:

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

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.

确保指定一个“默认”值,以防找不到标签。

回答by Kinjan Bhavsar

Try something like below

尝试像下面这样

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

where OrderXml is parent element.

其中 OrderXml 是父元素。

回答by Sarojini2064130

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

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

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

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