
com.alibaba.nacos.spring.util.parse.DefaultXmlConfigParse Maven / Gradle / Ivy
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.spring.util.parse;
import java.io.ByteArrayInputStream;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilderFactory;
import org.springframework.util.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.alibaba.nacos.api.config.ConfigType;
import com.alibaba.nacos.spring.util.AbstractConfigParse;
/*
lct-1
1006010022
major-1
hangzhou
123456
lct-2
1006010033
major-2
shengzheng
234567
lct-3
1006010044
major-3
wenzhou
345678
lct-4
1006010055
major-3
wuhan
456789
*/
/**
* Just support xml config like this
*
* @author liaochuntao
* @since 0.3.0
*/
public class DefaultXmlConfigParse extends AbstractConfigParse {
private DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
@Override
public Map parse(String configText) {
Map properties = new LinkedHashMap(8);
try {
Document document = factory.newDocumentBuilder()
.parse(new ByteArrayInputStream(configText.getBytes("UTF-8")));
Element root = document.getDocumentElement();
Map map = new LinkedHashMap(8);
recursionXmlToMap(map, root);
mapToProperties("", properties, map);
}
catch (Exception e) {
throw new ConfigParseException(e);
}
return properties;
}
private void recursionXmlToMap(Map outMap, Element element) {
NodeList nodeList = element.getChildNodes();
String name = element.getNodeName();
if (nodeList.getLength() == 1 && !nodeList.item(0).hasChildNodes()) {
addData(outMap, name, element.getTextContent());
}
else {
Map innerMap = new LinkedHashMap(1);
int length = nodeList.getLength();
for (int i = 0; i < length; i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element tElement = (Element) node;
recursionXmlToMap(innerMap, tElement);
}
}
addData(outMap, name, innerMap);
}
}
private void addData(Map map, String key, Object data) {
if (map.containsKey(key)) {
if (map.get(key) instanceof List) {
((List) map.get(key)).add(data);
}
else {
List
© 2015 - 2025 Weber Informatics LLC | Privacy Policy