从 XML 文件中可用的占位符获取变量名称的 Java 程序

问题描述 投票:0回答:1

希望你们一切都好。 我有一个要求,需要从 XML 文件中提供的占位符中选择变量名称。 我有一个包含所有占位符的 XML 文件,并且这些占位符以 $ 符号开头。 我的任务是获取该占位符,并从中获取变量名称。

例如,如果 XML 文件具有像 $Variable1 这样的占位符,那么它将从该占位符中获取 Variable1。

以下是我正在使用的代码:

public static String replaceConfigParam(String xmlFile, Object structure) {
    for (String key : getConstants(xmlFile)) {
        String actualKey = (new StringBuilder().append("$*").append(key).append("$")).toString();

        try {

            String value = BeanUtils.getProperty(structure, key);
            if (value != null) {
                xmlFile = xmlFile.replace(actualKey, value);
            }

        } catch (IllegalAccessException e) {
            logger.error("failed to get the property from  object " + e.getMessage());
        } catch (InvocationTargetException e) {
            logger.error("failed to get the property from  object" + e.getMessage());
        } catch (NoSuchMethodException e) {
            logger.error("failed to get the property from  object " + e.getMessage());
        } catch (Exception e) {
            logger.error("failed to get value from the property " + e.getMessage());
        }
    }
    return xmlFile;

以下是getConstant方法:

private static List<String> getConstants(String domainConfig) {
    String[] arr = domainConfig.split("\\$");
    List<String> paramsExtracted = new ArrayList<String>();
    for (String key : arr) {
        paramsExtracted.add(key.replace("$", ""));
                }
    return paramsExtracted;
}

以下是包含 $ 的 XML 文件,我需要从同一文件中提取变量:

<tunnel>
        <units>
          <entry name="tunnel.1">
            <ip>
              <entry name="$ABC"/>
            </ip>
            <interface-management-profile>mgt</interface-management-profile>
          </entry>
        </units>
      </tunnel> 
java xml jersey
1个回答
2
投票

我假设你的问题是:

“如何提取开头由 $ 符号标识的所有变量的条目名称属性”。

您可以使用正则表达式来完成此操作,但由于您正在使用 XML,因此您可以使用 Xpath + xpath 解析器。请看这里:

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class ExtractVar {

    static String xml = "<tunnel>" +
    "<units>" +
      "<entry name=\"tunnel.1\">"+
        "<ip>"+
       "   <entry name=\"$ABC\"/>"+
      "  </ip>"+
     "   <interface-management-profile>mgt</interface-management-profile>"+
    "  </entry>"+
   " </units>"+
  "</tunnel>";
    
    
    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = db.parse(new InputSource(new StringReader(xml)));
        
        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPathExpression xpath = xpathFactory.newXPath().compile("//entry");
        
        NodeList entryNodes = (NodeList) xpath.evaluate(document, XPathConstants.NODESET);
        for(int i =0; i<entryNodes.getLength(); i++) {
            Node n = entryNodes.item(i);
            String nodeValue = n.getAttributes().getNamedItem("name").getNodeValue();
            if(nodeValue.startsWith("$")) {
                System.out.println(nodeValue.substring(1, nodeValue.length()));
            }
        }
    }
}

以下代码的作用是:

  1. 将文档(您的 xml)解析为 DOM 模型。
  2. 为您要分析的属性创建 Xpath 表达式。在这种情况下,您希望所有节点都命名为“entry”,无论它们位于文档中的位置。这是通过在 Xpath
    //
    的开头执行
    //entry
    来实现的。
  3. 检索入口节点的 name 属性并检查它是否以美元符号开头。 4.如果属性值以 $ 符号开头,则打印属性值。

代码然后打印:

ABC

我希望这就是您正在寻找的。

或者,这可以通过纯正则表达式捕获每个被引号字符包围并以美元符号开头的字符串来实现,如下所示:

    Pattern pattern = Pattern.compile("\"\\$(.*)\"");
    Matcher matcher = pattern.matcher(xml);
    while(matcher.find()) {
        System.out.println(matcher.group(1));
    }
© www.soinside.com 2019 - 2024. All rights reserved.