Last active
December 10, 2015 12:38
-
-
Save mrmichalis/4435492 to your computer and use it in GitHub Desktop.
02/01/2012
Example Java XPath parsing and setting using org.dom2 http://www.jdom.org/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import org.jdom2.*; | |
import org.jdom2.filter.Filters; | |
import org.jdom2.input.*; | |
import org.jdom2.output.XMLOutputter; | |
import org.jdom2.xpath.XPathExpression; | |
import org.jdom2.xpath.XPathFactory; | |
import java.io.File; | |
import java.util.List; | |
import java.util.*; | |
public class Main { | |
private static void log(String aMessage) { | |
System.out.println(aMessage); | |
} | |
public static void main(String[] args) throws Exception { | |
for (String country_code : Arrays.asList(new String[]{"AU", "BE", "CA", "DE", "DK", "ES", "FI", "FR", "GB", "IE", "IT", "JP", "NL", "NO", "NZ", "SE", "US"})) { | |
try { | |
SAXBuilder saxBuilder = new SAXBuilder(); | |
Document doc_channel = saxBuilder.build(new FileReader("C:\\temp\\xmlp\\countries\\" + country_code + "\\channel-sets-" + country_code + ".xml")); | |
Document doc_cat = saxBuilder.build(new FileReader("C:\\temp\\xmlp\\countries\\" + country_code + "\\category-set-" + country_code + ".xml")); | |
XPathExpression<Element> xp_channel = XPathFactory.instance().compile("//channels/channel[@access='PREMIUM']", Filters.element()); | |
List<Element> channel_elements = xp_channel.evaluate(doc_channel); | |
for (Element channel_emt : channel_elements) { | |
log("Channel Element GUID " + channel_emt.getChild("tracks").getAttributeValue("guid") + " " + channel_emt.getName()); | |
String chn_code = channel_emt.getAttribute("code").getValue(); | |
if (chn_code.contentEquals("indie-rock-and-alternative-top-100")) { | |
log(" Change Channel Code set: " + chn_code); | |
chn_code = "indie-rock--alternative-top-100"; | |
} | |
XPathExpression<Element> xp_category = XPathFactory.instance().compile(".//categories/category[@code='" + chn_code + "']", Filters.element()); | |
List<Element> category_elemets = xp_category.evaluate(doc_cat); | |
for (Element cat_emt : category_elemets) { | |
for (Element target : cat_emt.getChildren("tracks")) { | |
//if (target.getAttributeValue("guid") == "") { | |
//log("Blank GUID " + target.getAttributeValue("guid")); | |
target.setAttribute("guid", channel_emt.getChild("tracks").getAttributeValue("guid")); | |
XMLOutputter xout = new XMLOutputter(); | |
xout.output(doc_cat, new FileOutputStream(new File("C:\\temp\\xmlp\\done\\" + country_code + "\\category-set-" + country_code + ".xml"))); | |
//} | |
} | |
} | |
} | |
} catch (Exception e) { | |
log(e.toString()); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment