JAVA:从XML Document中提取元素

时间:2013-03-11 18:05:45

标签: java xml

我正在使用javax.xml.parsers来浏览如下所示的XML文档:

`

<ContextElement>
    <DimensionNode>Role</DimensionNode>
    <Value>Administration</Value>
    <TailoringExpressions>
        <TailoringExpression>
            <Relation>Student</Relation>
            <ProjAtt>
                <Attribute>Matr</Attribute>
                <Attribute>SName</Attribute>
                <Attribute>SSurname</Attribute>
                <Attribute>SDateOfBirth</Attribute>
                <Attribute>SEmail</Attribute>
                <Attribute>SAddress</Attribute>
            </ProjAtt>
            <Condition/>
            <SemiJoinRel/>
            <SemiJoinOn/>
            <SemiJoinCond/>
        </TailoringExpression>
    </TailoringExpressions>
</ContextElement>
<ContextElement>
    <DimensionNode>Deadline</DimensionNode>
    <Value>Lost</Value>
    <TailoringExpressions>
        <TailoringExpression>
            <Relation>Deadline</Relation>
            <ProjAtt>
                <Attribute>IdDeadline</Attribute>
                <Attribute>Student</Attribute>                  
                <Attribute>DeadlineDate</Attribute>
                <Attribute>Description</Attribute>
                <Attribute>IsMet</Attribute>
            </ProjAtt>
            <Condition>DeadlineDate LT CurrentDate AND IsMet=False</Condition>
            <SemiJoinRel/>
            <SemiJoinOn/>
            <SemiJoinCond/>
        </TailoringExpression>
    </TailoringExpressions>
</ContextElement>

`

我有一个问题,因为我需要提取对象/节点ContextElement,其中DimensionNode的值为“Role”,Value为值“Administration”,我无法编写工作代码! 有人能告诉我该怎么做吗? 感谢

1 个答案:

答案 0 :(得分:0)

我认为提取值的最佳方法是使用xpath:

XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "/widgets/widget";
InputSource inputSource = new InputSource("widgets.xml");
NodeSet nodes = (NodeSet) xpath.evaluate(expression, inputSource, XPathConstants.NODESET);

有关详细信息,请查看oracle documentation