开发者

XInclude support in Java 6

开发者 https://www.devze.com 2023-04-12 12:36 出处:网络
I\'ve seen this example posted several time开发者_StackOverflows: public class XIncludeTest { public static void main(String[] args) throws Exception {

I've seen this example posted several time开发者_StackOverflows:

public class XIncludeTest {

  public static void main(String[] args) throws Exception {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      factory.setNamespaceAware(true);
      factory.setXIncludeAware(true);
      DocumentBuilder docBuilder = factory.newDocumentBuilder();
      System.out.println("isXIncludeAware " + docBuilder.isXIncludeAware());
      Document doc = docBuilder.parse(args[0]);

      Transformer transformer = TransformerFactory.newInstance().newTransformer();
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");

      //initialize StreamResult with File object to save to file
      StreamResult result = new StreamResult(new StringWriter());
      DOMSource source = new DOMSource(doc);
      transformer.transform(source, result);

      String xmlString = result.getWriter().toString();
      System.out.println(xmlString);    
    }
}

I pass this simple xml file in:

a.xml
<?xml version="1.0" encoding="UTF-8"?>
<a xmlns:xi="http://www.w3.org/2003/XInclude">
  <xi:include href="b.xml" xpointer="element(/b/c)"/>
  <xi:include href="b.xml" xpointer="element(/b/d)"/>
</a>

b.xml
<?xml version="1.0" encoding="UTF-8"?>
<b>
  <c>1</c>
  <d>2</d>
</b>

And all I get back out is the contents of a.xml, as above - no part of b.xml was included. I've tried endless variations on the xpointer syntax to no avail. I have, however, been able to get things to work in perl via XML::LibXML but I need this to work in Java.

What am I not getting?

OK, now I've updated my xml file to something that works:

a.xml
<?xml version="1.0" encoding="UTF-8"?>
<a xmlns:xi="http://www.w3.org/2001/XInclude">
  <xi:include href="b.xml" xpointer="element(/1/1)"/>
  <xi:include href="b.xml" xpointer="element(/1/2)"/>
</a>

I'd rather not use offsets into the document - names are much better (like in the first version of a.xml). I'm trying to understand XPointer Framework and have been using XPath and XPointer/XPointer Syntax as a reference as well - it seems I should be able to use a "shorthand" pointer but only if the NCName matches some ID-type attribute. Problem is that I don't have a DTD or schema that defines an "ID-type attribute". Given that the Java parser doesn't support the xpointer schema, is my only option to use indexes?


The namespace for the xi prefix should be "http://www.w3.org/2001/XInclude" (note 2001 not 2003). See http://www.w3.org/TR/xinclude/ for more details.

That gets you to what seems to be the next problem: the syntax of your element scheme xpointer is incorrect. See http://www.w3.org/TR/xptr-element/ for more information.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号