How to stop getNodeName () also print node type

I'm at a dead end, hopefully I just did a dumb thing that I can easily fix.

I pass a string full of XML, being "XMLstring". I want to get one of the elements and print the child nodes in "name = value" on the console. The problem is that the console continues to print garbage along with the name of the item that I cannot figure out how to get rid of.

In any case, this code:

try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(XMLstring));
        Document doc = db.parse(is);

        NodeList nodes = doc.getElementsByTagName("client-details");
        Node node = nodes.item(0);

        NodeList client_details = node.getChildNodes();

        for (int i = 0; i < client_details.getLength(); i++) {
            System.out.println(client_details.item(i).getNodeName()+" = "+getTextContents(client_details.item(i)));
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }

Gives me the following:

#text = 
testing-mode = false
#text = 
name = testman
#text = 
age = 30

Why is he typing "#text ="? How can I get rid of it?

I use NetBeans if this helps.

+3
source share
3 answers

OK , , . , Node , . :

try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(XMLstring));
        Document doc = db.parse(is);

        NodeList nodes = doc.getElementsByTagName("client-details");
        Node node = nodes.item(0);

        NodeList client_details = node.getChildNodes();

        Element elementary;

        for (int i = 0; i < client_details.getLength(); i++) {
            if(client_details.item(i).getNodeType() == Node.ELEMENT_NODE) {
                elementary = (Element) client_details.item(i);

                System.out.println(elementary.getTagName()+" = "+getTextContents(client_details.item(i)));
            }
        }
    }

, , "#text" :)

testing-mode = false
name = testman
age = 30

"if", for Node, getNodeName, Elements.

+1

getNodeValue():

System.out.println(client_details.item(i).getNodeValue()+" = "+getTextContents(client_details.item(i)));

, , getNodeName() #text.

+6

, System.out.println() , , . , , .

Otherwise, if you use String splitString = string.split("[=]");, it will split the line based on the '=' deminer

then you can

    String splitString = string.split("[=]");
    System.out.println(splitString[1] + " = " + splitString[2]);

or, more simply, do this one small edit posted by @retrodrone

+1
source

All Articles