【问题标题】:Parsing the XML for the schema location with Xstream使用 Xstream 解析模式位置的 XML
【发布时间】:2011-10-07 03:29:45
【问题描述】:

我无法使用 xstream 从 XML 中找出架构位置。

<order xmlns="http://www.mycompany.com/xml/myproject"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="test.xsd">

对于 XML 的验证,使用模式,我使用 javax :

Validator validator = schema.newValidator();
validator.validate(source);

目前我已将架构名称硬编码为“test.xsd”,但我希望这只是一个临时修复。

【问题讨论】:

    标签: java xsd xml-parsing xstream


    【解决方案1】:

    XStream 默认情况下不支持命名空间感知,但我认为您可以启用它。您应该能够在网站上找到详细信息。不过,要访问命名空间,您可以像对待任何其他属性一样对待它:

    public static void main(String[] args) {
        String xml = "<x:foo xmlns:x=\"http://foo.com\">" +
                             "<bar xmlns=\"http://bar.com\"/>" +
                             "</x:foo>";
        XStream xstream = new XStream();
        xstream.alias("x:foo", Foo.class);
        xstream.useAttributeFor(Foo.class, "xmlns");
        xstream.aliasField("xmlns:x", Foo.class, "xmlns");
        xstream.alias("bar", Bar.class);
        xstream.useAttributeFor(Bar.class, "xmlns");
        xstream.aliasField("xmlns", Foo.class, "xmlns");
        Object o = xstream.fromXML(xml);
        System.out.println("Unmarshalled a " + o.getClass());
        System.out.println("Value: " + o);
    }
    
    static class Foo {
        private String xmlns;
        private Bar bar;
        public String toString() {
            return "Foo{xmlns='" + xmlns + "', bar=" + bar + '}';
        }
    }
    
    static class Bar {
        private String xmlns;
        public String toString() {
            return "Bar{xmlns='" + xmlns + "'}";
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-09-19
      • 2017-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 2016-03-16
      • 1970-01-01
      • 2011-06-05
      相关资源
      最近更新 更多