获取标签以及值?XML [英] Getting tag as well as the values? XML
问题描述
我将以下 XML 作为字符串传递.
I have the following XML being passed as String.
<?xml version="1.0"?>
<tagMain>
<tag1>
<a>
<a>1</a>
<b>2</b>
<c>3</c>
<d>4</d>
</a>
<b>5</b>
<c>6</c>
<d>7</d>
<e>8</e>
<f>9</f>
</tag1>
<tag2>
<r>
<r1>10</r1>
<r2>11</r2>
<r3>12</r3>
<r4>13</r4>
</r>
<b>14</b>
<c>15</c>
<d>16</d>
<e>17</e>
<f>18</f>
</tag2>
<tag3>
<a>
<a>1m</a>
<b>2m</b>
<c>3m</c>
<d>4m</d>
</a>
<b>5m</b>
<c>6m</c>
<d>7m</d>
<e>8m</e>
<f>9m</f>
</tag3>
</tagMain>
我调用了以下方法,该方法为每个标签获取值.
I calling the following method which is getting me values between for each tag.
public static void SplitXml(String xml) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilder builder = DocumentBuilderFactory
.newInstance().newDocumentBuilder();
InputSource src = new InputSource();
src.setCharacterStream(new StringReader(xml));
Document docu = builder.parse(src);
String tag1 = docu.getElementsByTagName("tag1").item(0).getTextContent();
String tag2 = docu.getElementsByTagName("tag2").item(0).getTextContent();
String tag3 = docu.getElementsByTagName("tag3").item(0).getTextContent();
}
当我运行上面的代码时:
when I run the above code:
tag1 = "123456789";
tag2 = "101112131415161718";
tag3 = "1m2m3m4m5m6m7m8m9m";
现在我回到我的问题,有没有一种方法可以获得标签以及每个标签的内部值:
Now my back to my question, Is there a way I can get the tags as well as the values inside the like such for each tag:
tag1 = "<tag1><a>
<a>1</a>
<b>2</b>
<c>3</c>
<d>4</d>
</a>
<b>5</b>
<c>6</c>
<d>7</d>
<e>8</e>
<f>9</f>
</tag1>";
推荐答案
要么使用 LSSerializer
(http://docs.oracle.com/javase/8/docs/api/index.html?org/w3c/dom/ls/LSSerializer.html) 或从 TransformerFactory
创建一个默认的 Transformer
然后你可以使用它来序列化一个 DOM 节点,传入一个 DOMSource
到 transform
方法 (https://docs.oracle.com/javase/7/docs/api/javax/xml/transform/Transformer.html#transform(javax.xml.transform.Source,%20javax.xml.transform.Result) 和一个 StringWriter 来收集结果.
Either use LSSerializer
(http://docs.oracle.com/javase/8/docs/api/index.html?org/w3c/dom/ls/LSSerializer.html) or create a default Transformer
from a TransformerFactory
and then you can use that to serialize a DOM node, passing in a DOMSource
to the transform
method (https://docs.oracle.com/javase/7/docs/api/javax/xml/transform/Transformer.html#transform(javax.xml.transform.Source,%20javax.xml.transform.Result) and a StringWriter to collect the result.
这篇关于获取标签以及值?XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!