可能是一個新手問題,但是,我試圖用Java解析和更改ncx文件(重要的ePub格式),以確保PlayOrder屬性位於,正確的順序(1,2,3,4 ...)。 這是我的java到目前爲止,它工作得很好,但它將PlayOrder設置爲(1,3,5,7 ...)。猜猜它是解析一個標籤到很多()。有任何想法嗎?使用Java解析ncx(xml)以更改PlayOrder
package com.mkyong.common;
import java.io.File;
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.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class ModifyXMLFile {
public static void main(String argv[]) {
try{
String filepath = "toc.ncx";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);
//Get the root element
Node company = doc.getFirstChild();
//Get the staff element , it may not working if tag has spaces, or
//whatever weird characters in front...it's better to use
//getElementsByTagName() to get it directly.
//Node staff = company.getFirstChild();
//Get the staff element by tag name directly
Node navPoint = doc.getElementsByTagName("navMap").item(0);
//update staff attribute
/*NamedNodeMap attr = navPoint.getAttributes();
Node nodeAttr = attr.getNamedItem("navPoint");
nodeAttr.setTextContent("2");*/
//append a new node to staff
/*Element age = doc.createElement("age");
age.appendChild(doc.createTextNode("28"));
staff.appendChild(age);*/
//loop the staff child node
NodeList list = navPoint.getChildNodes();
for (int i =0; i<list.getLength();i++){
Node node = list.item(i);
//get the salary element, and update the value
NamedNodeMap attr = node.getAttributes();
if(attr != null){
Node nodeAttr = attr.getNamedItem("playOrder");
System.out.println(nodeAttr);
String aString = Integer.toString(i);
nodeAttr.setTextContent(aString);
}
}
//write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filepath));
transformer.transform(source, result);
System.out.println("Done");
}catch(ParserConfigurationException pce){
pce.printStackTrace();
}catch(TransformerException tfe){
tfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}catch(SAXException sae){
sae.printStackTrace();
}
}
}
值得一提的是,playOrder屬性在EPUB 2.0.1棄用,不再需要在所有。 EPX 3中也完全刪除了NCX。 – 2011-05-25 21:44:48