gpt4 book ai didi

java - 在 XML 标签之间跳转

转载 作者:行者123 更新时间:2023-12-02 00:54:35 25 4
gpt4 key购买 nike

这是SAX中的一个疑问。我想处理 XML 文件中的子标签,前提是它与父标签匹配。例如:

<version>
<parent tag-1>
<tag 1>
<tag 2>
</parent tag-1 >
<parent tag-2>
<tag 1>
<tag 2>
</parent tag-2>
</version>

在上面的代码中,我想首先匹配父标签(即父标签-1或父标签``-2,基于用户输入),然后才处理其下的子标签。这可以在 SAX 解析器中完成吗?请记住,SAX 对 DOM 的控制有限,而且我在 SAX 和 Java 方面都是新手?如果有的话,能否引用一下相应的方法?TIA

最佳答案

当然,通过记住父标签就可以轻松完成。

一般来说,在解析 xml 标签时,人们使用堆栈来跟踪这些标签的家族图。使用以下代码可以轻松解决您的问题:

Stack<Tag> tagStack = new Stack<Tag>();

public void startElement(String uri, String localName, String qName,
Attributes attributes)
if(localName.toLowerCase().equals("parent")){
tagStack.push(new ParentTag());
}else if(localName.toLowerCase().equals("tag")){
if(tagStack.peek() instanceof ParentTag){
//do your things here only when the parent tag is "parent"
}
}
}
public void endElement(String uri, String localName, String qName)
throws SAXException{
if(localName.toLowerCase().equals("parent")){
tagStack.pop();
}
}

或者您可以通过更新标记名来记住您所在的标记:

String tagName = null;
public void startElement(String uri, String localName, String qName,
Attributes attributes)
if(localName.toLowerCase().equals("parent")){
tagName = "parent";
}else if(localName.toLowerCase().equals("tag")){
if(tagName!= null && tagName.equals("parent")){
//do your things here only when the parent tag is "parent"
}
}
}
public void endElement(String uri, String localName, String qName)
throws SAXException{
tagName = null;
}

但我更喜欢堆栈方式,因为它会跟踪所有祖先标签。

关于java - 在 XML 标签之间跳转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1443347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com