Home About
XML

いわゆる PI と呼ばれる ProcessingInstruction に JDOM でアクセスする方法

こんな XML文書があったときに <?xml-stylesheet href="style.xsl" type="text/xsl"?> に 該当する内容に JDOM でアクセスするにはどうしたらいいの?という話。

<?xml version="1.0"?>
<?xml-stylesheet href="style.xsl" type="text/xsl"?>
<html>
<body><h1>hello</h1></body>
</html>

org.jdom2.Document で getContent() するだけだった

@Grab(group='org.jdom', module='jdom', version='2.0.2')

import org.jdom2.*
import org.jdom2.input.*

xmldata='''<?xml version="1.0"?>
<?xml-stylesheet href="style.xsl" type="text/xsl"?>
<html>
<body><h1>hello jdom</h1></body></html>
'''

def doc = new SAXBuilder().build( new StringReader(xmldata) )
println doc.getContent()

ついでに再帰的に要素をたどって getContent() するコードもメモ

@Grab(group='org.jdom', module='jdom', version='2.0.2')

import org.jdom2.*
import org.jdom2.input.*

xmldata='''<?xml version="1.0"?>
<?xml-stylesheet href="style.xsl" type="text/xsl"?>
<html>
<body><h1>hello jdom</h1></body></html>
'''

recur = { def obj , int indent ->
	println '  '*indent + obj.toString().replaceAll('\n','')
	if( obj instanceof Parent ){
        obj.content.each{
            recur(it , indent+1 )
        }
	}
}

def doc = new SAXBuilder().build( new StringReader(xmldata) )
recur(doc,0)

実行結果はこれです。

[Document:  No DOCTYPE declaration, Root is [Element: <html/>]]
  [ProcessingInstruction: <?xml-stylesheet href="style.xsl" type="text/xsl"?>]
  [Element: <html/>]
    [Text: ]
    [Element: <body/>]
      [Text: ]
      [Element: <h1/>]
        [Text: hello jdom]
      [Text: ]
    [Text: ]

JDOM 便利ですね。

Liked some of this entry? Buy me a coffee, please.