gpt4 book ai didi

java - xml解析字符串匹配Java

转载 作者:行者123 更新时间:2023-11-30 07:18:45 24 4
gpt4 key购买 nike

我正在尝试从文件夹中解析一堆 xml 文件并返回包含特定表达式的所有标签。以下是我所做的,

public class MyDomParser {

public static void main(String[] args) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
File folder = new File("C:\\Users\\xmlfolder");

DocumentBuilder builder = factory.newDocumentBuilder();
for(File workfile : folder.listFiles()){
if(workfile.isFile()){
Document doc = builder.parse(workfile);

}
}
}


} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

如何循环遍历每个 XML 中的所有标记并返回包含表达式“/server[^<]*”的标记。

非常感谢任何帮助。

最佳答案

您可以创建一个单独的方法,递归地遍历当前 XML 文件中的所有节点,并将匹配的标签添加到节点列表中。

示例:

public static void parseTags (Node node, List<Node> list)
{
NodeList nodeList = node.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++)
{
Node n = nodeList.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE)
{
String content = n.getTextContent();

// if the tag content matches your criteria, add it to the list
if (content.matches("/server[^<]*"))
{
list.add(n);
}
parseTags(n, list);
}
}
}

您可以在现有代码中调用此方法,如下所示:

// create your list outside the loop like this:
List<Node> list = new ArrayList<Node>();

for(File workfile : folder.listFiles())
{
if(workfile.isFile())
{
Document doc = builder.parse(workfile);

// call the recursive method here:
parseTags(doc.getDocumentElement(), list);
}
}

关于java - xml解析字符串匹配Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37958832/

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