将XML元素更改为String

时间:2016-01-29 20:37:55

标签: java xml dom xpath

我想知道在使用DOM解析器时是否有一种简单的方法可以将XML元素更改为字符串。

我在这里有一些代码:

XPathExpression NtryRefexpr = xpath.compile("//Ntfctn/Ntry/NtryRef");
            Object NtryRef = NtryRefexpr.evaluate(doc, XPathConstants.NODESET);
            NodeList nodesNtryRef = (NodeList) NtryRef;
            for(int i = 0; i < nodesNtryRef.getLength(); i++){
                Element NtryRefel = (Element) nodesNtryRef.item(i);
                String element = NtryRefel.toString();
                NtryRefAL.add(element);


            }

你可以收集我试图在XML元素上使用.toString()。显然这没有用,因为当我回去尝试打印数组中的项时,一切都为空。此外,当我尝试只打印字符串“element”时,它也显示为null。

将“element”转换为String的正确方法是什么? XML中元素的实际值只是一堆数字。

1 个答案:

答案 0 :(得分:0)

我终于通过研究和其他人的帮助弄明白了这一点。

下面是我的代码,显示我如何浏览节点,选择我想要的节点并将属性保存到String。请注意,该属性将包含许多额外信息,包括标记名称

示例:

<?xml version="1.0" encoding="UTF-8"?><NachaTransCd>27</NachaTransCd>

因此必须使用子字符串和length方法删除它。

这是我的代码:

XPathExpression CardAcctTpexpr = xpath.compile("//Ntfctn/Ntry/NtryDtls/TxDtls/SplmtryData/Envlp/Cnts/CardAcctTp");
            Object CardAcctTp = CardAcctTpexpr.evaluate(doc, XPathConstants.NODESET);
            NodeList nodesCardAcctTp = (NodeList) CardAcctTp;
            for(int i = 0; i < nodesCardAcctTp.getLength(); i++){
                Element CardAcctTpel = (Element) nodesCardAcctTp.item(i);
                CardAcctTpS = Utilities.xmlToString(CardAcctTpel);
                int length = CardAcctTpS.length();
                CardAcctTpS = CardAcctTpS.substring(50,length);
                length = CardAcctTpS.length();
                CardAcctTpS = CardAcctTpS.substring(0,length-13);
                CardAcctTpAL.add(CardAcctTpS);

            }
相关问题