我是 JAVA 的新手,我想读取文本文件并用 XML 编写它,这是我的输入:
- R.-J。Roe, J. Appl.Phys。36, 2024 (1965)。
和输出但是是:
<ref id="1">
<label>1</label>
<citation-alternatives>
<mixed-citation>R.-J. Roe, J. Appl.Phys. 36, 2024 (1965).</mixed-citation>
</citation-alternatives>
</ref>
在许多情况下,此输入分为两行,它们之间没有空格,如下所示:
R.-J。鱼子,
J.应用物理。36, 2024 (1965)。
输出将是这样的:
<ref id="1">
<label>1</label>
<citation-alternatives>
<mixed-citation>R.-J. Roe, </mixed-citation>
</citation-alternatives>
</ref>
<ref id="1">
<label>1</label>
<citation-alternatives>
<mixed-citation>J. Appl.Phys. 36, 2024 (1965).</mixed-citation>
</citation-alternatives>
</ref>
现在我的问题是我怎样才能把这两行读成一个像第一个输出一样的东西?这是我的代码:
try {
String strLine;
String num="";
String mix="";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// Back element
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("Back");
doc.appendChild(rootElement);
// ref-list element
Element reflist = doc.createElement("ref-list");
rootElement.appendChild(reflist);
while( (strLine = br.readLine()) != null)
{
if (strLine.equals("")) {
continue;
}
int dotIndex = strLine.indexOf(".");
num = strLine.substring(0,dotIndex);
mix = strLine.substring(dotIndex+2,strLine.length());
// ref element
Element ref= doc.createElement("ref");
reflist.appendChild(ref);
// set attribute of ref element
Attr attr = doc.createAttribute("id");
attr.setValue(num);
ref.setAttributeNode(attr);
// label element
Element label = doc.createElement("label");
ref.appendChild(label);
label.setTextContent(num);
// citation-alternatives element
Element citationalternatives = doc.createElement("citation-alternatives");
ref.appendChild(citationalternatives);
// mixed-citation element
Element mixedcitation = doc.createElement("mixed-citation");
citationalternatives.appendChild(mixedcitation);
mixedcitation.setTextContent(mix);
}