How to delete #text from my node parsing in Java DOM XML parsing

So I have the following code that I almost copied from here The problem is that my text nodes don't contain any text, they only have attributes So I like it

<Random name="Katie" num="5"></Random>

I'm using this code to parse it:

private void listNodes(Node node,String indent)
  {
    String nodeName = node.getNodeName();
    System.out.println(indent + " Node is: " + nodeName);

    if(node instanceof Element && node.hasAttributes())
    {
      System.out.println(indent + "Attributes are: ");
      NamedNodeMap attrs = node.getAttributes();
      for (int i = 0; i < attrs.getLength(); i++) 
      {
        Attr attribute = (Attr) attrs.item(i);
        System.out.println(indent + attribute.getName() + "=" + attribute.getValue());
      }
    }

    NodeList list = node.getChildNodes(); 

    if (list.getLength() > 0) 
    {
      for (int i = 0; i < list.getLength(); i++)
      {
        listNodes(list.item(i),indent + " "); 
      } 
    }
  }

For some reason, my empty text nodes say

Who knows how to skip empty node text when parsing XML files?

thank you,

joke

Solution

With DTD validation, you can let the parser automatically suppress whitespace between elements However, to modify a particular implementation, you can test the text nodes and ignore them if they are empty

private void listNodes(Node node,String indent)
{
    if (node instanceof Text) {
        String value = node.getNodeValue().trim();
        if (value.equals("") ) {
            return;
        }
    }

    String nodeName = node.getNodeName();
    System.out.println(indent + " Node is: " + nodeName);
    ...
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>