2012-05-25 45 views
1

我正在使用R的XML包提取各种html和xml文件中的所有可能的数据。这些文件基本上是文档或构建属性或自述文件。R XML包解析xml和html文件时的怪异错误

<?xml version='1.0' encoding='utf-8'?> 
<!DOCTYPE chapter PUBLIC '-//OASIS//DTD DocBook XML V4.1.2//EN' 
         'http://www.oasis-open.org/docbook/xml/4.0 docbookx.dtd'> 

<chapter lang="en"> 
<chapterinfo> 
<author> 
<firstname>Jirka</firstname> 
<surname>Kosek</surname> 
</author> 
<copyright> 
<year>2001</year> 
<holder>Ji&rcaron;&iacute; Kosek</holder> 
</copyright> 
<releaseinfo>$Id: htmlhelp.xml,v 1.1 2002/05/15 17:22:31 isberg Exp $</releaseinfo> 
</chapterinfo> 
<title>Using XSL stylesheets to generate HTML Help</title> 
<?dbhtml filename="htmlhelp.html"?> 

<para>HTML Help (HH) is help-format used in newer versions of MS 
Windows and applications written for this platform. This format allows 
to pack several HTML files together with images, table of contents and 
index into single file. Windows contains browser for this file-format 
and full-text search is also supported on HH files. If you want know 
more about HH and its capabilities look at <ulink 
url="http://msdn.microsoft.com/library/tools/htmlhelp/chm/HH1Start.htm">HTML 
Help pages</ulink>.</para> 

<section> 
<title>How to generate first HTML Help file from DocBook sources</title> 

<para>Working with HH stylesheets is same as with other XSL DocBook 
stylesheets. Simply run your favorite XSLT processor on your document 
with stylesheet suited for HH:</para> 

</section> 

</chapter> 

我的目标是只使用xmlValue解析使用htmlTreeParse或使用这样的事情xmlTreeParse树后(用于XML文件..)

Text = xmlValue(xmlRoot(xmlTreeParse(XMLFileName))) 

然而,有一个错误当我这样做为xml和html文件。如果有2级或更多级别的子节点,则文本字段会在它们之间没有任何空间的情况下被粘贴。

例如,在上面的例子中

xmlValue(chapterInfo)是

JirkaKosek2001JiKosek$Id: htmlhelp.xml,v 1.1 2002/05/15 17:22:31 isberg Exp 

每一子节点的xmlValues(递归),而不在它们之间增加空间粘贴在一起。我怎样才能得到xmlValue添加一个空格,而提取该数据

非常感谢您的帮助提前,

Shivani

+0

如果解决了您的问题,请务必接受答辩人的答案。您可以通过选择响应旁边的勾号来做到这一点。 –

回答

3

根据该文件,xmlValue只在单个文本节点工程 ,或在“包含单个文本节点的XML节点上”。 非文本节点中的空格显然不被保留。

但是,即使在单个文本节点的情况下,您的代码也会去掉空白。

library(XML) 
doc <- xmlTreeParse("<a> </a>") 
xmlValue(xmlRoot(doc)) 
# [1] "" 

您可以ignoreBlanks=FALSEuseInternalNodes=TRUE 参数添加到xmlTreeParse,保留所有的空白。

doc <- xmlTreeParse(
    "<a> </a>", 
    ignoreBlanks = FALSE, 
    useInternalNodes = TRUE 
) 
xmlValue(xmlRoot(doc)) 
# [1] " " 

# Spaces inside text nodes are preserved 
doc <- xmlTreeParse(
    "<a>foo <b>bar</b></a>", 
    ignoreBlanks = FALSE, 
    useInternalNodes = TRUE 
) 
xmlValue(xmlRoot(doc)) 
# [1] "foo bar" 

# Spaces between text nodes (inside non-text nodes) are not preserved 
doc <- xmlTreeParse(
    "<a><b>foo</b> <b>bar</b></a>", 
    ignoreBlanks = FALSE, 
    useInternalNodes = TRUE 
) 
xmlValue(xmlRoot(doc)) 
# [1] "foobar" 
+0

谢谢文森特那是有帮助的。这就像一个魅力 –