使用xpath e4.emf.xpath.XPathContext查询EMF模型

时间:2017-01-11 09:38:28

标签: java xml xpath e4 emf

我有一个emf模型,我根据某些条件从中选择了EObjects。

为此,我尝试使用org.eclipse.e4.emf.xpath.XPathContext。但是XPATH表达式没有给出任何结果。

以下是示例xml

<?xml version="1.0" encoding="ASCII"?>
   <codeAnalysis xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:noNamespaceSchemaLocation="http://myTool/codeAnalysis/CommonReport">
<Header>
<Title>My_Report</Title>
<Date>02/05/2016</Date>
<CreatedBy>xyz</CreatedBy>
<Software>
  <checkpoint>0</checkpoint>
  <StartComponent>ABC</StartComponent>
  <StartFolder>E:\TestProject</StartFolder>
</Software>
<Environment>
  <Version>8.1.2</Version>
  <ToolVersion>1.33.0.qualifier</ToolVersion>      
</Environment>
</Header>
<Report>
<Component name="MSI">
    <File name="TestProject/comp/a.h">
        <Function name="TIME_STAMP_GET_TIMER_VALUE">
            <Complain lfd="1">
                <MetricName>STM29</MetricName>
                <Value>0</Value>
             </Complain>
        </Function>
    </File>
</Component>
</Report>
</codeAnalysis>

我想获得codeAnalysis / Header / Software / StartComponent

的值

以下是我写的代码

    public void emfQueryTest() {
    try {
        String filePath = "E:\\03Projects\\Test.xml";
        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xml", new MetricCommonReportResourceFactoryImpl());
        resourceSet.getPackageRegistry().put(MetricCommonReportPackage.eNS_URI, MetricCommonReportPackage.eINSTANCE);
        Resource resource = (Resource)resourceSet.getResource(URI.createFileURI(filePath), true);
        if (resource != null) {
            resource.load(Collections.EMPTY_MAP);
            if (resource.getContents() != null && resource.getContents().size() > 0) {
                CodeAnalysis metricCodeAnalysis = (MetricCommonReport.CodeAnalysis) resource.getContents().get(0);
                System.out.println(metricCodeAnalysis.getHeader().getTitle());
                XPathContextFactory<EObject> f = EcoreXPathContextFactory.newInstance();
                XPathContext xPathContext = f.newContext(metricCodeAnalysis);
                Iterator<MetricCommonReport.Software> it = xPathContext.iterate("/codeAnalysis/Header/Software");                   

                while( it.hasNext() ) {
                    System.out.println("Hello");
                    System.out.println("    " + it.next().getStartComponent());
                }  
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

正确加载此xml。但它不会为startComponent打印任何值。事实上Iterator它没有任何元素?哪里出错了?请有人纠正我。

Java中的相同XPath表达式提供了正确的节点和值。

0 个答案:

没有答案