有多种方法可以表示同一个 XML 文档(见下文),空格和引号的差异可能会使编写(和维护)正则表达式变得困难。
input.xml(表示 1)
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg" contentScriptType="text/ecmascript" width="1024" zoomAndPan="magnify" contentStyleType="text/css" viewBox="0 0 1024 768" height="768" preserveAspectRatio="xMidYMid meet" version="1.0">
input.xml(表示 2)
<?xml version="1.0" encoding="UTF-8"?>
<svg
xmlns:xlink = 'http://www.w3.org/1999/xlink'
xmlns = 'http://www.w3.org/2000/svg'
contentScriptType = 'text/ecmascript'
width = '1024'
zoomAndPan = 'magnify'
contentStyleType = 'text/css'
viewBox = '0 0 1024 768'
height = '768'
preserveAspectRatio = 'xMidYMid meet'
version = '1.0'>
我建议使用 XML 解析器。下面是如何使用StAX (JSR-173)完成它。StAX 解析器的实现包含在 Java SE 6 中。
演示
package forum12193899;
import java.io.StringReader;
import javax.xml.stream.*;
import javax.xml.transform.stream.StreamSource;
public class Demo {
public static void main(String[] args) throws Exception {
XMLInputFactory xif = XMLInputFactory.newFactory();
StreamSource xml = new StreamSource("src/forum12193899/input.xml");
String xmlString = "<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns=\"http://www.w3.org/2000/svg\" contentScriptType=\"text/ecmascript\" width=\"1024\" zoomAndPan=\"magnify\" contentStyleType=\"text/css\" viewBox=\"0 0 1024 768\" height=\"768\" preserveAspectRatio=\"xMidYMid meet\" version=\"1.0\">";
XMLStreamReader xsr = xif.createXMLStreamReader(new StringReader(xmlString));
xsr.nextTag(); // Advance to "svg" element.
int attributeCount = xsr.getAttributeCount();
String[] array = new String[attributeCount];
for(int x=0; x<attributeCount; x++) {
StringBuilder stringBuilder = new StringBuilder();
array[x]= xsr.getAttributeLocalName(x) + "=\"" + xsr.getAttributeValue(x) + "\"";
}
// Output the Array
for(String string : array) {
System.out.println(string);
}
}
}
输出
contentScriptType="text/ecmascript"
width="1024"
zoomAndPan="magnify"
contentStyleType="text/css"
viewBox="0 0 1024 768"
height="768"
preserveAspectRatio="xMidYMid meet"
version="1.0"