このような {HT,X}ML で正規表現を使用しない理由についての SO の質問を読んだことがあります -- Regex to Indent an XML Fileですが、私が書いた関数を投稿すると思いましたが、それは絶対に何もしませんが、従属のレベルに基づいて XML 行をインデントします。
SOのガイドラインを満たすために、私は危険にさらされます-私のソリューションを整理します:-)、そう--
この関数を使用して、名前のない悪意のある人物がインデントなしで送信した XML ファイルをフォーマットすると、何が問題になるでしょうか?
xmlit <- function(x,indchar = '\t'){
# require x to be a vector of char strings, one
# per line of the XML file.
# Add an indent for every line below one starting "<[!/]" and
# remove an indent for every line below "</"
indit <-''
y<-vector('character',length(x))
for(j in 1:length(x) ) {
# first add whatever indent we're up to
y[j] <- paste(indit,x[j],collapse='',sep='')
# check for openers: '<' but not '</' or '/>'
if( grepl('<[^/?!]' ,x[j]) & !grepl('/>', x[j]) & !grepl('</',x[j]) ) {
indit<-paste(indit,indchar,collapse='',sep='')
} else {
# check for closers: '</'
if( grepl('<[/]' ,x[j]) & !grepl('<[^/?!]',x[j]) ) {
# move existing line back out one indent
y[j]<- substr(y[j],2,1000)
indit<-substr(indit,2,1000)
}
}
}
# Note that I'm depending on every level to have a matching closer,
# and that in particular the very last line is a closer.
return(invisible(y))
}