java—尝试迭代xml文件中非常相似的元素注意xml文件没有属性

inkz8wg9  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(324)

我有一个关于xml和java的问题。我有一个奇怪的xml文件,没有属性,只有元素,我试图在一个特定的元素堆栈上归零,然后遍历所有类似的元素堆栈。

<InstrumentData>
    <Action>Entire Plot</Action>
    <AppStamp>Vectorworks</AppStamp>
    <VWVersion>2502</VWVersion>
    <VWBuild>523565</VWBuild>
    <AutoRot2D>false</AutoRot2D>
    <UID_1505_1_1_0_0>   ---- This is the part I care about, there are about 1000+ of these and they all vary slightly after the "UID_"---
      <Action>Update</Action>
      <TimeStamp>20200427192323</TimeStamp>
      <AppStamp>Vectorworks</AppStamp>
      <UID>1505.1.1.0.0</UID>
    </UID_1505_1_1_0_0>

我使用dom4j作为xml解析器,在输出所有数据时没有任何问题,我只想在xml路径上归零。
这是目前为止的代码:

public class Unmarshal {

    public Unmarshal() {
        File file = new File("/Users/michaelaboah/Desktop/LIHN 1.11.18 v2020.xml");
        SAXReader reader = new SAXReader();
        try {
            Document doc = reader.read(file);       
            Element ele = doc.getRootElement();
            Iterator<Element> it = ele.elementIterator();
            Iterator<Node> nodeIt = ele.nodeIterator();

            while(it.hasNext()) {
                Element test2 = (Element) it.next();
                List<Element> eleList = ele.elements();

                for(Element elementsIt : eleList) {
                    System.out.println(elementsIt.selectSingleNode("/SLData/InstrumentData").getStringValue());
                        //This spits out everything under the Instrument Data branch
                        //All of that data is very large

                    System.out.println(elementsIt.selectSingleNode("/SLData/InstrumentData/UID_1505_1_1_0_0").getStringValue());
                        //This spits out everything under the UID branch
                }
            }

        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

另外,我知道有一些未使用的数据类型和变量有很多测试

hmtdttj4

hmtdttj41#

我想你的答案是:

elementsIt.selectSingleNode("/SLData/InstrumentData/*[starts-with(local-name(), 'UID_')]").getStringValue()

我用这篇文章找到了这个xpath,它只适用于您给出的几行xml。

相关问题