【问题标题】:Parsing XML type file解析 XML 类型文件
【发布时间】:2017-02-19 02:36:36
【问题描述】:

我正在使用 Java,我需要从一个 AutomationML 文件(XML 类型文件)中获取信息。我尝试使用 JAXB 来做到这一点,但最终我无法获得所需的信息。 在 AML 中,我有一个带有 3 个具有一些属性的 InternalElements 的 InstanceHierarchy,我需要这些属性值,但是使用 JAXB 我得到了 AttributeName 但我无法得到它的值。

public static void main(String[] args) throws Exception {

    CAEXFile caex = null;
    CAEXFile.InstanceHierarchy ih = null;
   try {

        JAXBContext jc = JAXBContext.newInstance(CAEXFile.class);
        //JAXBContext jc = JAXBContext.newInstance(generated.CAEXFile.InstanceHierarchy.class);
        Unmarshaller ums = jc.createUnmarshaller();
        CAEXFile aml = (CAEXFile)ums.unmarshal(new File("src\\teste2.aml"));

        System.out.println("ins = " + aml.getInstanceHierarchy().get(0).getInternalElement().get(0).getAttribute().get(0).getName());

  } catch (JAXBException e) {
    System.out.println(e.getMessage());
  }
}

xsd 文件 XSD (CAEX) 和 AML 文件 AML 有人可以帮助我使用 JAXB 或给我一些如何解决这个问题的指导吗? 提前致谢。

【问题讨论】:

    标签: java xml xsd xml-parsing jaxb


    【解决方案1】:

    您实际上可以完全避免使用 JAXB,这取决于您的代码的其余部分。如果您可以使用 Java 8,也许 Dynamics 将是一个不错且直接的解决方案。

    XmlDynamic example = new XmlDynamic(xmlStringOrReaderOrInputSourceEtc);
    
    String firstInternalName = example.get("CAEXFile|InstanceHierarchy|InternalElement|@Name").asString();
    // TestProduct_1
    
    List<String> allInternalNames = example.get("CAEXFile").children()
        .filter(hasElementName("InstanceHierarchy")) // import static alexh.weak.XmlDynamic.hasElementName;
        .flatMap(Dynamic::children)
        .filter(hasElementName("InternalElement"))
        .map(internalElement -> internalElement.get("@Name").asString())
        .collect(toList());
    // [TestProduct_1, TestResource_1, TestProduct_2, TestProduct_3, TestResource_2]
    

    这是一个单一且轻量级的额外依赖,即在 maven 中:

    <dependency>
      <groupId>com.github.alexheretic</groupId>
      <artifactId>dynamics</artifactId>
      <version>2.3</version>
    </dependency>
    

    【讨论】:

    • 感谢您的回复,我用双重解组解决了;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-12
    • 2017-11-04
    • 2011-11-20
    相关资源
    最近更新 更多