2016-10-10 99 views
1

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

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或者给我一些方向如何解决这个问题? 在此先感谢。

回答

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] 

这是一个轻便的额外的依赖,即行家:

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

感谢您的答复,我带双解组解决;) –