String tagName = "crminfo"; logger.info(xmlResponse); List<Map<String, Object>> parsedXmlData = DataParserUtil.parseXml(xmlResponse, tagName, fieldMapping); logger.info("parsedXmlData: " + parsedXmlData);
public static List<Map<String, Object>> parseXml(String xml, String tagName, FieldMapping fieldMapping) throws Exception {
if (StringUtils.isBlank(xml)) {
return new ArrayList<>();
}
// Remove BOM if present
if (xml.startsWith("\uFEFF")) {
xml = xml.substring(1);
}
// Remove ZWNBSP if present
xml = xml.replaceAll("\uFEFF", "");
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml)));
NodeList nodeList = document.getElementsByTagName(tagName);
List<Map<String, Object>> xmlObjects = new ArrayList<>();
Map<String, String> fieldMap = fieldMapping.getFieldMap();
for (int i = 0; i < nodeList.getLength(); i++) {
Element element = (Element) nodeList.item(i);
Map<String, Object> objectMap = new HashMap<>();
// Collect all attributes and their values
NamedNodeMap attributes = element.getAttributes();
for (int j = 0; j < attributes.getLength(); j++) {
Node attribute = attributes.item(j);
String keyName = attribute.getNodeName();
for (String jsonField : fieldMap.keySet()) {
String xmlField = fieldMap.get(jsonField);
if (StringUtils.equals(keyName, xmlField)) {
keyName = jsonField;
break;
}
}
String value = attribute.getNodeValue();
ValueConverter converter = fieldMapping.getConverter(keyName);
objectMap.put(keyName, converter != null ? converter.convert(value) : value);
}
xmlObjects.add(objectMap);
}
return xmlObjects;
}
我希望像这样添加值
parsedXmlData=[{firstName=Direct_Lens_01、middleInit=、lastName=automation_test、zipCode=、国家/地区=CAN、businessUnit=、authorizedRepNo=、城市=、afslNo=、companyName=、电话=12345678、}]
但我得到 ParsedXMLData=[{}]
需要指导来改进此代码并获取值
`
根据您的输入和输出期望,我尝试编写解决方案,我正在粘贴完整的解决方案,尝试一下并根据您的要求进行调整
public class XmlUtil {
public static void main(String[] args) {
String xmlString = """
<awd>
<crminfo>
<UserProfile>
<FirstName>Direct Lens 01</FirstName>
<MiddleInit />
<LastName>automation test</LastName>
<CompanyName />
<Email>[email protected]</Email>
<Phone>123456789</Phone>
<Address1>123 hello st</Address1>
<Address2>unit 4439</Address2>
<City>Toronto</City>
<State>ON</State>
<ZipCode>M5H 2R2</ZipCode>
<Country>CAN</Country>
<Province />
<Zip>M5H 2R2</Zip>
<ProfessionalDesignation />
<Website />
<BusinessRegistrationNo />
<AfslNo />
<AuthorisedRepNo />
<Custodian />
<TransferAgent />
<Address3 />
<JobTitle />
<BusinessUnit />
<FirmType>Academic/Library</FirmType>
<JobFunction>Fund Analysis</JobFunction>
</UserProfile>
</crminfo>
</awd>
""";
List<Map<String, String>> userProfile = parsedXMldata(xmlString, "UserProfile");
userProfile.stream().forEach(System.out::println);
}
public static List<Map<String,String>> parsedXMldata(String xml, String tagName) {
List<Map<String, String>> result;
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
db = dbf.newDocumentBuilder();
Document sourceDoc = db.parse(new InputSource(new StringReader(xml)));
sourceDoc.getDocumentElement().normalize();
NodeList UserProfile = sourceDoc.getElementsByTagName("UserProfile");
result = new ArrayList<>();
for (int x = 0, size = UserProfile.getLength(); x < size; x++) {
//for each user profile print all their nodes
NodeList profile = UserProfile.item(x).getChildNodes();
System.out.println();
Map<String, String> map = new LinkedHashMap<>();
for (int i = 0; i < profile.getLength(); i++) {
if (profile.item(i).getNodeType() == Node.ELEMENT_NODE) {
//System.out.println(profile.item(i).getNodeName() + " : " + profile.item(i).getTextContent());
map.put(profile.item(i).getNodeName(), profile.item(i).getTextContent());
}
}
result.add(map);
}
} catch (ParserConfigurationException | SAXException | IOException e) {
throw new RuntimeException(e);
}
return result;
}
}