有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用HTML从XML节点获取内容

我有一个REST服务返回XML,但是在一些XML内容中,有HTML标记。当我循环遍历XML节点时,似乎只有一个。getTextContent()方法,用于剥离内容中的HTML。有没有其他方法可以在不剥离HTML的情况下获取内容

我创建的用于获取XML节点内容和属性的函数

来电者:

String firstName = RESTHelper.getXMLProperty(xmlData, "rootNode/person/firstName");

方法:

public static String getXMLProperty(String xml, String searchNodes) {
    String retVal = "";
    String[] nodeSplit = searchNodes.split("/");

    if(xml.trim().length()==0)
        return retVal;

    try 
    {  
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        Document doc;
        NodeList nList;

        DocumentBuilder builder = factory.newDocumentBuilder();
        doc = builder.parse( new InputSource( new StringReader( xml )) );

        nList = doc.getElementsByTagName(nodeSplit[0]);
        retVal = GetXMLNode(nList, searchNodes, 0);
    } catch (Exception e) {  
        e.printStackTrace();  
    } 

    return retVal;
}

private static String GetXMLNode(NodeList nl, String searchNodes, int item)
{
    String retVal = null;
    String findNode = searchNodes.split("/")[item];
    int count = searchNodes.split("/").length;

    item++;

    for(int i=0; i<nl.getLength(); i++) {
        String foundNode = nl.item(i).getNodeName();
        NamedNodeMap nnm = nl.item(i).getAttributes();
        if(nnm!=null && nnm.getLength()>0 && count>item) {
            Node attribute = nnm.getNamedItem(searchNodes.split("/")[item]);
            if(attribute!=null) {
                retVal = attribute.getTextContent();  //returns only text
                break;
            }
        }

        if(foundNode.equals(findNode) && count>item) {
            retVal = GetXMLNode(nl.item(i).getChildNodes(), searchNodes, item);
            break;
        } else if(foundNode.equals(findNode) && count==item) {
            retVal = nl.item(i).getTextContent(); //returns only text
            break;
        }
    }

    return retVal;
}

共 (1) 个答案

  1. # 1 楼答案

    最后,我让REST服务为包含HTML的节点返回Base64,然后UI将其转换回来