首页 > 解决方案 > 使用 SaxParser 修改 xml 属性

问题描述

我有一个 XML,在其中我想使用 SAXParser 为特定节点修改链接属性的

我确实找到了https://stackoverflow.com/a/51662488/9681353并且我在我的案例中使用了 Attributes2Impl。

到目前为止我所拥有的:

SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();

UpdateLinksHandler linksHandler = new UpdateLinksHandler();
saxParser.parse(xml, linksHandler);
@Override
    public void startElement(String uri, String key, String qName, Attributes attributes) throws SAXException {
        if (qName.equalsIgnoreCase(USEROBJECT)) {
            String link = attributes.getValue("link");
            if (link != null) {
                Attributes2 attrs = (Attributes2) attributes;
                Attributes2Impl newAttrs = new Attributes2Impl();
                for (int i = 0; i < attrs.getLength(); i++) {
                    if (attrs.isSpecified(i)) {
                        String type = attrs.getType(i);
                        String value = attrs.getValue(i);
                        String name = attrs.getQName(i);
                        if (name == "link") {
                            value = modifyLink(value);
                        }
                        newAttrs.addAttribute(null, null, name, type, modifyLink(value));
                    }
                }
                super.startElement(uri, key, qName, newAttrs);
            }
        }

但我不知道我的方法是否正确,或者我应该如何获取修改后的 xml。还是 SAXParser 仅用于阅读目的?

谢谢

标签: javaxmlsaxsaxparser

解决方案


推荐阅读