简体   繁体   English

解析 XML 类型文件

[英]Parsing XML type file

I'm using Java, and I need to get information from one AutomationML file (XML type file).我正在使用 Java,我需要从一个 AutomationML 文件(XML 类型文件)中获取信息。 I try to use JAXB to do that but in the end I can't get the information I need.我尝试使用 JAXB 来做到这一点,但最终我无法获得所需的信息。 In AML I have one InstanceHierarchy with 3 InternalElements with some attributes, and I need that attributes values, but using JAXB I get the AttributeName but I can't get its value.在 AML 中,我有一个 InstanceHierarchy,其中包含 3 个 InternalElements 和一些属性,我需要这些属性值,但是使用 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());
  }
}

The xsd file XSD (CAEX) and AML file AML Can someone help me using JAXB or give me some directions how to solve this? xsd 文件XSD (CAEX)和 AML 文件AML有人可以帮助我使用 JAXB 或给我一些如何解决这个问题的指导吗? Thanks in advance.提前致谢。

You can actually avoid JAXB altogether, which can be useful depending on the rest of your code.您实际上可以完全避免 JAXB,这取决于您的代码的其余部分。 If you can use Java 8 perhaps Dynamics would be a nice & direct solution.如果您可以使用 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]

It's a single and lightweight extra dependency, ie in maven:这是一个单一且轻量级的额外依赖项,即在 maven 中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM