java下string与html、xml互转操作

能帅
2023-12-01

添加的pom.xml

<dependency>
	<groupId>org.jsoup</groupId>
	<artifactId>jsoup</artifactId>
	<version>1.11.3</version>
</dependency>

<dependency>
	<groupId>org.dom4j</groupId>
	<artifactId>dom4j</artifactId>
	<version>2.1.3</version>
</dependency>

string和html互转操作

    public static String html2str(){
    
       String htmlStr = "<div sb_id=\"001\"><input type=\"text\"servyou_type=\"string\"id=\"001_58_1\"><input type=\"text\"servyou_type=\"string\"class=\"sssqq\"></div>";
       	//字符串转html
        final Document document = Jsoup.parse(html);

        //根据id 获取节点 修改值
		document.getElementById("001_58_1").val("1111").attr("title","1111");
		
		//根据class 获取节点
		document.getElementsByClass("sssqq").val("22222").attr("title","22222");

		//根据属性 获取节点
        document.getElementsByAttributeValue("sb_id","001").attr("sb_title","测试属性获取值");
        Element body = document.body();
        
        //html转字符串
        System.out.println(body.toString());
    }

string和xml 互转操作

public static void xml2str(){
        String xml = "<sites><site><name>RUNOOB</name><url>www.runoob.com</url></site><site><name>Google</name><url>www.google.com</url></site><site><name>Facebook</name><url>www.facebook.com</url></site></sites>";
        //string  转 xml
        org.dom4j.Document xmlDocument = org.dom4j.DocumentHelper.parseText(xml);
        if(xmlDocument!=null){
            //获取根节点
            org.dom4j.Element rootElement = xmlDocument.getRootElement();

            //获取根节点下所有 内容
            List<Node> content = rootElement.content();
            //获取节点 并赋值
            org.dom4j.Element node = (org.dom4j.Element)content.get(0);
            node.element("name").setText("测试");
            node.element("url").setText("测试url");
            //xml转string   打印
            System.out.println(rootElement.asXML());  //这种方式如果值为空,xml标签不会闭合(<name></name>会显示成</name>)
            System.out.println(asXML(rootElement));  //解决空值xml标签不会闭合问题
        }
}

解决值为空 标签不闭合问题


// 转换为标准格式(避免自闭合的问题)
    private static String asXml(Element body) {
        OutputFormat format = new OutputFormat();
        format.setEncoding("UTF-8");
        format.setExpandEmptyElements(true);
        StringWriter out = new StringWriter();
        XMLWriter writer = new XMLWriter(out, format);
        try {
            writer.write(body);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out.toString();
    }
 类似资料: