简体   繁体   English

使用Java替换一组重复的xml标签

[英]Replace a set of repetitive xml tags using Java

I need to replace a bunch of xml tags with a unique TAG, I found a solution but I am not sure it's the best out there... What would you propose? 我需要用一个唯一的TAG替换一堆xml标记,我找到了一个解决方案,但是我不确定这是最好的。您会提出什么建议?

/** Group tags replacement.
 * @param input <mytag><tag>val1</tag><tag>val2</tag></mytag>
 * @param tag tag
 * @param replacement <tag>val</tag>
 * @return <mytag><tag2>value</tag2></mytag>
 */
public static String replaceGroupTags(String input, String tag, String replacement) {
    Pattern replace = Pattern.compile("<" + tag + ">" + ".*" + "</" + tag + ">");
    Matcher matcher = replace.matcher(input);

    int start = Integer.MIN_VALUE;
    int end = Integer.MAX_VALUE;
    while (matcher.find()) {
        if (start == Integer.MIN_VALUE) start = matcher.start();
        if (end <= Integer.MAX_VALUE) end = matcher.end();
    }
    StringBuffer stringBuffer = new StringBuffer(input);
    return stringBuffer.replace(start, end, replacement).toString();
}

Trying to parse XML using regex is a bad idea. 尝试使用正则表达式解析XML是一个坏主意。 Here is a solution using DOM : 这是使用DOM的解决方案:

public static void replaceGroupTags(File input, File output, String tag, String replacement) {
             Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(inputFile));

            XPath xpath = XPathFactory.newInstance().newXPath();
            NodeList nodes = (NodeList)xpath.evaluate("//SomeNode/" + tag, doc, XPathConstants.NODESET);

            // replace all occurences
            for (int i = 0; i < nodes.getLength(); i++) {
              nodes.item(i).setTextContent(replacement);
            }

            // save result to the file 
            Transformer xformer = TransformerFactory.newInstance().newTransformer();
            xformer.transform(new DOMSource(doc), new StreamResult(output);
    }

It traverses through file, finds all occurrences of tag inside SomeNode node and replaces its content with replacement 它遍历文件,查找SomeNode节点内所有出现的tagSomeNode其内容replacement

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM