利用dom4j判断xml文件的格式是否正确的方法,解析失败就会报错,DocumentBuilderFactory.newInstance();

首先得到:得到 DOM 解析器的工厂实例      

DocumentBuilderFactory domfac=DocumentBuilderFactory.newInstance();

然后从 DOM 工厂获得 DOM 解析器

 DocumentBuilder dombuilder=domfac.newDocumentBuilder();

3 )把要解析的 XML 文档转化为输入流,以便 DOM 解析器解析它
 

Document parse = (Document) builder.parse(new ByteArrayInputStream(xmlStr.getBytes(StandardCharsets.UTF_8)));

这里其实也不用获取解析后的返回值了,如果解析失败就会抛出异常了。

案例分析加完整代码:

使用方法代码:

//xml文件的string类型内容
String xmlData = "      ";
Dom4jUtils.isXmlDocument(xmlData);

我这里是将该验证方法放在了Dom4j这个工具类中.

Dom4j工具类:

public class Dom4jUtils {

    //定义日志记录器
    private static Logger logger = LoggerFactory.getLogger(Dom4jUtils.class);

    /**
     * 验证 xml格式是否正确
     * @param xmlStr xmlStr
     * @throws Exception Exception
     */
    public static void isXmlDocument(String xmlStr) throws Exception{
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
        builder.parse(new ByteArrayInputStream(xmlStr.getBytes(StandardCharsets.UTF_8)));
    }
}

这个方法没有返回东西,因为只是验证xml格式是否正确的方法,若报错就是不正确即可。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值