我是 JAVA 新手,我想读取文本文件并将其写入 XML,这是我的输入:
- R.-J。罗伊,J.应用物理学。 2024 年 36 日(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.应用物理学。 2024 年 36 日(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);
}
最佳答案
在将 strLine 插入元素之前,检查是否有 strLine.endsWith( ","),如果是,则读取下一行(依此类推)并附加到第一个 strLine。
关于java - 需要帮助来读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15587106/