我在String变量
中有这样的XML文件 <?xml version="1.0" encoding="UTF-8"?>
<customer>
<partyId>1000010700</partyId>
<CustomerAccount>
<accountType>2</accountType>
<companyCode>6001</companyCode>
<circleId>MU</circleId>
<accountID>400000005901</accountID>
<subscriptionType>1</subscriptionType>
</CustomerAccount>
<CustomerAccount>
<accountType>1</accountType>
<companyCode>6000</companyCode>
<circleId>MU</circleId>
<accountID>100000011972</accountID>
<subscriptionType>1</subscriptionType>
<Identifier>
<value>7021137076</value>
</Identifier>
</CustomerAccount>
<emailId>sonia.mathew@ril.com</emailId>
<telephoneNumber>+917376452847</telephoneNumber>
<name>
<salutation>0002</salutation>
<firstName>raghu</firstName>
<middleName />
<lastName>sanity</lastName>
</name>
<Product>
<id>P10016</id>
<name>VOLTE-VVM-DATA</name>
<contractRefNumber />
<productStatus>Z020</productStatus>
<alias />
<productStatusDescription />
<activationDate>2016-02-18 10:09:09.0</activationDate>
<Identifier>
<name>MSISDN</name>
<type />
<value>7021137076</value>
<subCategory>2</subCategory>
<category>4</category>
</Identifier>
<ProductRelationship>
<specificationId />
<Identifier>
<name>MSISDN</name>
<type />
<value>7021137076</value>
<subCategory>2</subCategory>
<category>4</category>
</Identifier>
</ProductRelationship>
<Service>
<name>VOICE VIDEO MESSAGING.</name>
<Identifier>
<name>MSISDN</name>
<value>917021137076</value>
<subCategory>3</subCategory>
<category>2</category>
</Identifier>
<id>S40001</id>
<PlanSpecification />
<ServiceSpecification>
<serviceType>Z0003</serviceType>
</ServiceSpecification>
</Service>
<Service>
<name>VOLTE-DATA</name>
<Identifier>
<name>IMSI</name>
<value>405874888888172</value>
<subCategory>3</subCategory>
<category>2</category>
</Identifier>
<id>S40002</id>
<PlanSpecification />
<ServiceSpecification>
<serviceType>Z0002</serviceType>
</ServiceSpecification>
</Service>
<BusinessInteractionType>
<name>CUGGRPDL</name>
</BusinessInteractionType>
<BusinessInteractionType>
<name>CUGADMEM</name>
</BusinessInteractionType>
<BusinessInteractionType>
<name>MSISDNCH</name>
</BusinessInteractionType>
<BusinessInteractionType>
<name>FFMODIFY</name>
</BusinessInteractionType>
<BusinessInteractionType>
<name>FFDELETN</name>
</BusinessInteractionType>
<BusinessInteractionType>
<name>CUGGRPCR</name>
</BusinessInteractionType>
<BusinessInteractionType>
<name>CUGDLMEM</name>
</BusinessInteractionType>
<BusinessInteractionType>
<name>FFCREATE</name>
</BusinessInteractionType>
<BusinessInteractionType>
<name>SIMCHNGE</name>
</BusinessInteractionType>
<BusinessInteractionType>
<name>SSUSPEND</name>
</BusinessInteractionType>
<BusinessInteractionType>
<name>RMSRVFTR</name>
</BusinessInteractionType>
<BusinessInteractionType>
<name>SRVCEASE</name>
</BusinessInteractionType>
<BusinessInteractionType>
<name>ADSRVFTR</name>
</BusinessInteractionType>
<BusinessInteractionType>
<name>OGBARING</name>
</BusinessInteractionType>
<BusinessInteractionType>
<name>DNDSERVC</name>
</BusinessInteractionType>
<ProductOffering>
<id>OC4508</id>
<name>VOLTE REGULAR OFFER</name>
</ProductOffering>
<customerAccount>
<accountID>100000011972</accountID>
</customerAccount>
<billingType>1</billingType>
<type>1</type>
</Product>
<preferredCommunicationChannel>INT</preferredCommunicationChannel>
<preferredLanguage>EN</preferredLanguage>
<segment>
<attributeName>CUSTOMER_CATEGORY</attributeName>
<attributeValue>0001</attributeValue>
</segment>
</customer>
<actions>
<element>NMBTRNFO</element>
<element>CUGADMEM</element>
<element>MOBTRNFR</element>
<element>NMBTRNFR</element>
<element>MSISDNCH</element>
<element>CUGGRPCR</element>
<element>CUGGRPDL</element>
<element>SSUSPEND</element>
<element>SRVCEASE</element>
<element>CUGDLMEM</element>
<element>FFDELETN</element>
<element>RMSRVFTR</element>
<element>FFMODIFY</element>
<element>FFCREATE</element>
<element>ASSOUSER</element>
<element>ADSRVFTR</element>
<element>DNDSERVC</element>
<element>DISOUSER</element>
</actions>
=============================================
我一直把XML作为String传递给我的servlet
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public test() {
super();
}
protected Node getNode(String tagName, NodeList nodes) {
for ( int x = 0; x < nodes.getLength(); x++ ) {
Node node = nodes.item(x);
if (node.getNodeName().equalsIgnoreCase(tagName)) {
return node;
}
}
return null;
}
protected String getNodeValue( Node node ) {
NodeList childNodes = node.getChildNodes();
for (int x = 0; x < childNodes.getLength(); x++ ) {
Node data = childNodes.item(x);
if ( data.getNodeType() == Node.TEXT_NODE )
return data.getNodeValue();
}
return "";
}
protected String getNodeValue(String tagName, NodeList nodes ) {
for ( int x = 0; x < nodes.getLength(); x++ ) {
Node node = nodes.item(x);
if (node.getNodeName().equalsIgnoreCase(tagName)) {
NodeList childNodes = node.getChildNodes();
for (int y = 0; y < childNodes.getLength(); y++ ) {
Node data = childNodes.item(y);
if ( data.getNodeType() == Node.TEXT_NODE )
return data.getNodeValue();
}
}
}
return "";
}
protected String getNodeAttr(String attrName, Node node ) {
NamedNodeMap attrs = node.getAttributes();
for (int y = 0; y < attrs.getLength(); y++ ) {
Node attr = attrs.item(y);
if (attr.getNodeName().equalsIgnoreCase(attrName)) {
return attr.getNodeValue();
}
}
return "";
}
protected String getNodeAttr(String tagName, String attrName, NodeList nodes ) {
for ( int x = 0; x < nodes.getLength(); x++ ) {
Node node = nodes.item(x);
if (node.getNodeName().equalsIgnoreCase(tagName)) {
NodeList childNodes = node.getChildNodes();
for (int y = 0; y < childNodes.getLength(); y++ ) {
Node data = childNodes.item(y);
if ( data.getNodeType() == Node.ATTRIBUTE_NODE ) {
if ( data.getNodeName().equalsIgnoreCase(attrName) )
return data.getNodeValue();
}
}
}
}
return "";
}
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
/ * protected void service(HttpServletRequest request,HttpServletResponse response)抛出ServletException,IOException {
System.out.println("*************************************");
System.out.println(response.toString());
//System.out.println(inp.toString());
System.out.println(request.toString());
}*/
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// doGet(request, response);
try {
ArrayList<Object> al= new ArrayList<>();
String req=request.getParameter("Text1");
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(req));
Document doc = db.parse(is);
NodeList nodes = doc.getElementsByTagName("partyId");
for (int i=0; i < nodes.getLength();)
{
doc.renameNode(nodes.item(i), "", "customerId");
}
nodes = doc.getElementsByTagName("Product");
for (int i=0; i < nodes.getLength();)
{
doc.renameNode(nodes.item(i), "", "products");
}
nodes = doc.getElementsByTagName("CustomerAccount");
for (int i=0; i < nodes.getLength();)
{
doc.renameNode(nodes.item(i), "", "accounts");
}
nodes = doc.getElementsByTagName("telephoneNumber");
for (int i=0; i < nodes.getLength();)
{
doc.renameNode(nodes.item(i), "", "mobileNumber");
}
nodes= doc.getElementsByTagName("customer");
Element root = doc.getDocumentElement();
Element contDet = doc.createElement("contactDetails");
nodes = doc.getElementsByTagName("mobileNumber");
contDet.appendChild(nodes.item(0));
nodes = doc.getElementsByTagName("emailId");
contDet.appendChild(nodes.item(0));
root.appendChild(contDet);
nodes = doc.getElementsByTagName("ProductRelationship");
for (int i=0; i < nodes.getLength();)
{
doc.renameNode(nodes.item(i), "", "dependancyInfo");
}
nodes = doc.getElementsByTagName("BusinessInteractionType");
for (int i=0; i < nodes.getLength();)
{
doc.renameNode(nodes.item(i), "", "actions");
}
nodes = doc.getElementsByTagName("Service");
for (int i=0; i < nodes.getLength();)
{
doc.renameNode(nodes.item(i), "", "customerFacingServices");
}
nodes = doc.getElementsByTagName("customerAccount");
for (int i=0; i < nodes.getLength();)
{
doc.renameNode(nodes.item(i), "", "accountIds");
}
NodeList ndListFirstFile = doc.getElementsByTagName("actions");
for (int i=0; i < nodes.getLength();)
{
Node nodeArea = doc.getElementsByTagName("name").item(0);
ndListFirstFile.item(0).appendChild(nodeArea);
}
//Renaming name of action to element
NodeList root12 = doc.getChildNodes();
Node comp = getNode("customer", root12);
Node exec = getNode("products", comp.getChildNodes() );
NodeList nodes32 = exec.getChildNodes();
nodes32=doc.getElementsByTagName("actions");
for ( int x = 0; x < nodes32.getLength(); x++ ) {
Node node = nodes32.item(x);
System.out.println(node.getNodeName());
if (node.getNodeName().equalsIgnoreCase("actions")) {
NodeList childNodes = node.getChildNodes();
for (int y = 0; y < childNodes.getLength(); y++ ) {
// Node data = childNodes.;
Node abc= doc.getElementsByTagName("name").item(0);
//Node data= abc.getNextSibling();
//if(abc.hasChildNodes())
doc.renameNode(abc, "", "element");
// System.out.println( data.getNodeValue());
}
}
}
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
System.out.println(xmlString);
System.out.println(doc.toString());
Element element = (Element)nodes.item(0);
} catch (Exception e) {
e.printStackTrace();
}
}
答案 0 :(得分:0)
以下是一些代码,但它仅适用于您的任务:
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException,
TransformerConfigurationException, TransformerException {
DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
f.setValidating(false);
DocumentBuilder builder = f.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));
Node root = doc.getFirstChild();
NodeList rootChilds = root.getChildNodes();
Node product = null;
// Searching "name" and "Product" tags
for (int i = 0, j = rootChilds.getLength(); i < j; i++) {
Node item = rootChilds.item(i);
if ("name".equals(item.getNodeName())) {
doc.renameNode(item, item.getNamespaceURI(), "PersonalDetails");
}
if ("Product".equals(item.getNodeName())) {
product = item;
break;
}
}
// Creating "actions" tag
Node actions = doc.createElement("actions");
product.appendChild(actions);
// Removing "BusinessInteractionType" tag and copy its value to "element" tag
for (int i = 0, j = product.getChildNodes().getLength(); i < j; i++) {
Node item = product.getChildNodes().item(i);
if (item != null && "BusinessInteractionType".equals(item.getNodeName())) {
String value = item.getFirstChild().getNextSibling().getTextContent();
Element element = doc.createElement("element");
element.appendChild(doc.createTextNode(value));
actions.appendChild(element);
product.removeChild(item);
--i;
}
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
DOMSource domSource = new DOMSource(doc);
StreamResult streamResult = new StreamResult(new StringWriter());
transformer.transform(domSource, streamResult);
System.out.println(streamResult.getWriter().toString());
}
答案 1 :(得分:0)
如果要将XML元素转换为不同的XML元素,则需要使用XSLT:
static void extractBusinessActions(String xml,
Result result)
throws TransformerException {
String xslt =
"<?xml version='1.0'?>\n" +
"<xsl:stylesheet" +
" xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" +
" version='1.0'>\n" +
" <xsl:template match='//Product'>\n" +
" <actions>\n" +
" <xsl:for-each select='BusinessInteractionType/name'>\n" +
" <element><xsl:value-of select='.'/></element>\n" +
" </xsl:for-each>\n" +
" </actions>\n" +
" </xsl:template>\n" +
" <xsl:template match='text()|@*'/>\n" +
"</xsl:stylesheet>\n";
Transformer transformer =
TransformerFactory.newInstance().newTransformer(
new StreamSource(new StringReader(xslt)));
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(new StreamSource(new StringReader(xml)), result);
}