import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
public class XML {
public static void main(String argv[]) {
try {
String outputPath = "C:/Users/mwrona/XMLe/New/";
File fXmlDir = new File("C:/Users/mwrona/XMLe/");
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
File[] xmls = fXmlDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.getName().toLowerCase().endsWith(".xml");
}
});
for (File xmlFile : xmls) {
processFile(xmlFile, docBuilder, outputPath);
}
System.out.println("Done");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
}
}
private static void processFile(File xmlFile, DocumentBuilder docBuilder,
String outputPath) throws TransformerException, SAXException,
IOException {
Document doc = docBuilder.parse(xmlFile);
Node nList = doc.getElementsByTagName("DeliveryPoint").item(0);
Node nList2 = doc.getElementsByTagName("Order-Parties").item(0);
/*Element newElement = doc.createElement("NowyObiekt"); //dodanie nowej pozycji
newElement.appendChild(doc.createTextNode("NowaWartosc"));
nList.appendChild(newElement);*/
NodeList list = nList.getChildNodes();
Element orig = (Element) nList;
//kopiowanie drzewa
Element New = (Element) orig.cloneNode(true);
nList2.appendChild(New);
NodeList nodes = doc.getElementsByTagName("DeliveryPoint");
for (int i = 0; i < nodes.getLength(); i++) {
doc.renameNode(nodes.item(1), null, "UltimateCustomer");
}
Node nList3 = doc.getElementsByTagName("UltimateCustomer").item(0);
NodeList list2 = nList3.getChildNodes();
for (int i = 0; i < list2.getLength(); i++) {
Node node = list2.item(i);
//usuniecie
if ("ILN".equals(node.getNodeName())) {
nList3.removeChild(node);
}
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(outputPath, "" + xmlFile.getName()));
transformer.transform(source, result);
}
}