【发布时间】:2011-06-29 17:34:26
【问题描述】:
所以我发现可以使用缓冲的读取器/写入器将 xml 文件逐字逐句地复制到新的 xml 文件中。但是,我想知道是否可以只刮掉文档的一部分?
例如看这个例子:
<?xml version="1.0" encoding="UTF-8"?>
<BookCatalogue xmlns="http://www.publishing.org">
<w:pStyle w:val="TOAHeading" />
<Book>
<Title>Yogasana Vijnana: the Science of Yoga</Title>
<author>Dhirendra Brahmachari</Author>
<Date>1966</Date>
<ISBN>81-40-34319-4</ISBN>
<Publisher>Dhirendra Yoga Publications</Publisher>
<Cost currency="INR">11.50</Cost>
</Book>
<Book>
<Title>The First and Last Freedom</Title>
<v:imagedata r:id="rId7" o:title="" croptop="10523f" cropbottom="11721f" />
<Author>J. Krishnamurti</Author>
<Date>1954</Date>
<ISBN>0-06-064831-7</ISBN>
<Publisher>Harper & Row</Publisher>
<Cost currency="USD">2.95</Cost>
</Book>
<w:pStyle w:val="TOAHeading2" />
</BookCatalogue>
对不起,如果这不是正确的 XML 代码,我只是将我正在查看的文档中的花絮添加到我找到的这个示例中。但基本上,如果我想查找“标题”的一个实例(在本例中为第 3 行 -> TOAHeading),则从标题向下抓取所有内容,直到找到另一个标题实例并将其复制到另一个 xml 文件。那可能吗?此外,如果我想将其作为我要存储的临时文件,并且仅在找到“图像”实例(在本例中为第 14 行)时才保留该文件,这也可能吗?我正在尝试以最简单的方式做到这一点,那么有人对此有任何想法或经验吗?提前致谢。
public class IPDriver
{
public static void main(String[] args) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStreamReader("C:/Documents and Settings/user/workspace/Intern Project/Proposals/Converted Proposals/Extracted Items/ProposalOne/word/document.xml"), "UTF-8"));
BufferedWriter writer = new BufferedWriter(new OutputStreamReader(new FileOutputStreamReader("C:/Documents and Settings/user/workspace/Intern Project/Proposals/Converted Proposals/Extracted Items/ProposalOne/word/tempdocument.xml"), "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null)
{
writer.write(line);
}
// Close to unlock.
reader.close();
// Close to unlock and flush to disk.
writer.close();
}
}
我的实际 XML 文档中的示例
- <w:smartTag w:uri="urn:schemas-microsoft-com:office:smarttags" w:element="address">
- <w:smartTag w:uri="urn:schemas-microsoft-com:office:smarttags" w:element="Street">
- <w:r w:rsidRPr="00822244">
<w:t>6841 Benjamin Franklin Drive</w:t>
</w:r>
</w:smartTag>
</w:smartTag>
</w:p>
- <w:p w:rsidR="00B41602" w:rsidRPr="00822244" w:rsidRDefault="00B41602" w:rsidP="007C3A42">
- <w:pPr>
<w:pStyle w:val="Address" />
</w:pPr>
- <w:smartTag w:uri="urn:schemas-microsoft-com:office:smarttags" w:element="City">
- <w:smartTag w:uri="urn:schemas-microsoft-com:office:smarttags" w:element="place">
只是来自 .docx 的基本 document.xml 文件
【问题讨论】:
-
@maasg 不。从事一个项目(工作),这只是较大项目的一部分,但我对使用 xml 相当陌生
-
我个人会使用 xmlparser 库(例如 dom4j),但是如果你有这个要求,为什么不逐行扫描文件并检查每一行是否包含“标题”一词。如果是,则开始编写下一行,直到找到包含“标题”的另一行。同时,您还可以检查某行是否包含“
”。一旦你来到第二个“标题”,你就会根据你的结果存储或删除临时文件。然而,这是一种幼稚的实现,正如我所说,出于多种原因,使用 xml 库会更好
标签: java xml parsing file-io xml-parsing