例如,我有这个文件 XML:
<http auto-config="true">
<intercept-url access="ROLE_ADMIN,ROLE_USER" pattern="/"/>
<intercept-url access="ROLE_ADMIN,ROLE_USER" pattern="/index*"/>
<intercept-url access="ROLE_ADMIN" pattern="/page1"/>
<intercept-url access="ROLE_ADMIN" pattern="/page2"/>
<intercept-url access="ROLE_ADMIN" pattern="/page33"/>
</http>
我想更改这一行元素“访问”的文本:
<intercept-url access="ROLE_ADMIN" pattern="/page33"/>
所以我创建了这段代码:
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.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.sun.xml.internal.ws.org.objectweb.asm.Attribute;
public class ChangeXMLFile {
public static void main(String argv[]) {
try {
String filepath = "D:\\Myfile.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);
Node company = doc.getFirstChild();
Node staff = doc.getElementsByTagName("intercept-url").item(0);
NodeList list = staff.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
if ("pattern".equals(node.getNodeName())) {
if(("/page33").equals(node.getTextContent())){
NamedNodeMap attr = staff.getAttributes();
Node nodeAttr = attr.getNamedItem("access");
nodeAttr.setTextContent("ROLE_ANONYM");
}
}
}
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();
}
}
}
但我没有零钱。如何让程序读取xml文件的每一行,根据“pattern”的内容Text改变“access”属性?