【问题标题】:Need to extract xsi:type attribute value using SAX parser需要使用 SAX 解析器提取 xsi:type 属性值
【发布时间】:2013-05-07 05:18:48
【问题描述】:

我想从 XML 中提取 xsi:type 属性值,如下所示

<interface xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="SerialInterface">

我想在这里提取 xsi:type 属性值,即 SerialInterface

我试图使用node.getAttributeValue,但这并不完全有效

【问题讨论】:

    标签: java xml sax


    【解决方案1】:

    我会使用 StAX。

        XMLStreamReader xr = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(s));
        xr.next();
        String type = xr.getAttributeValue(0);
    

    请注意,我使用了属性索引 0。这是因为 XML 解析器不返回 xmlns:xsi attr。

    这是基于 SAX 的版本

        String s = "<interface xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"SerialInterface\" />";
        final StringBuilder type = new StringBuilder();
        SAXParserFactory.newInstance().newSAXParser()
                .parse(new ByteArrayInputStream(s.getBytes()), new DefaultHandler() {
                    @Override
                    public void startElement(String uri, String localName, String qName,
                            Attributes attrs) throws SAXException {
                        if (type.length() == 0) {
                            type.append(attrs.getValue("xsi:type"));
                        }
                    }
                });
        System.out.println(type);
    

    输出

    SerialInterface
    

    【讨论】:

    • 我必须使用 SAX,并且我有一个“元素”类型的节点。我可以使用 node.getAttributeValue() 之类的东西来获取它吗?
    • 你确定你需要 SAX 而不是 DOM?
    • 是的,其余部分由 SAX 完成。所以现在不能改变。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-02
    • 2014-03-16
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    相关资源
    最近更新 更多