Страница 1 из 1

How inside of XML doc to refer to this doc location?

Добавлено: 01 мар 2007, 18:58
Demurrage
Hi Folks,

I was wondering if it possible to refer to the location of an XML doc within itself.

The isssue is as follows:

I am using the XInclude processing instruction to include an XML doc (y.xml)
into some another XML doc (x.xml), so

x.xml looks like this:

<x xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="y.xml" parse="xml"/>
</x>

Both x.xml and y.xml reside within the same location of the same jar.

Parsing of x.xml fails, due to the fact that the parser is looking for y.xml in the application working directory i.e. c:\intellij\project, and not where the xml files in fact reside:
org.xml.sax.SAXParseException: Include operation failed. Resource error reading file as XML (href='y.xml'). Reason: c:\intellij\project\y.xml (The system cannot find the file specified)

As per system requirements though, I can only use a relative path to the xml files and not an absolute path (e.g. file://c:/myjar.jar!/y.xml) because depending on the deployment schema, the actual location of the files may vary. The only thing which will always remain the same is files' location in relation to one another i.e. same directory.

So my question is how within an xml doc to refer to where this doc resides (if it is in fact possible)?

Thanks in adavance

PS. this message was actually intented for Java/XML-specific forums and in fact has been posted there already. I just thought that it wouldn't hurt to re-post it here, just in case if by any chance some XML guru is hanging around here :-)

Добавлено: 01 мар 2007, 22:47
Ranger
по-русски хоть можно отвечать или только на собачьей мове? ;)

мысль. попробуй написать свой EntityResolver

P.S. кстати, Xinclude - это ни в коем случае не "processing instruction" :wink:

Добавлено: 02 мар 2007, 11:33
Demurrage
Спасибо попробую.

Добавлено: 02 мар 2007, 14:08
Earl Grey
А почему вы не можете просто читать реальный XML document; превращать его в XML node и реально вставлять его (не ссылку) в другой документ?

Добавлено: 02 мар 2007, 16:19
Marmot
Хмм, даже интересно стало, я тут потрепался с нашими XML gurus про то как заставить XInclude читать из текушей директории документа.
Они теперь ходят, чешут затылки :), надавали мне кучу емейлов других гуров которые могут об этом знать.
Будем искать даьше :)
Пока только известно, что специфицировано это в XML Base: http://www.w3.org/TR/2001/REC-xmlbase-20010627/.
Но там такой случай не описан :(
Еще сказали, что по идее, парсер должен подбирать файлы именно из директории где находится документ а не из CWD...
Короче бардак :)

Добавлено: 02 мар 2007, 19:20
vg
Если тебе надо вставить в документ другой документ, то делается просто

<?xml version="1.0"?>

<!DOCTYPE Config
[
<!ENTITY includeddoc SYSTEM "specific-config.xml">
]
>

<Config
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="config.xsd">

...
...
...
<!--==================== Это ты вставляешь твой документ в том месте где надо =================== -->
&includeddoc;
...
...
...

</Config>

Добавлено: 05 мар 2007, 10:45
Demurrage
This approach has failed with the same error, unable to locate the xml doc to include i.e. specific-config.xml. Once again, the the doc to include was being looked for in the folder the JVM was executed in and not from the Jar, where the original xml doc resides.
vg писал(а):Если тебе надо вставить в документ другой документ, то делается просто

<?xml version="1.0"?>

<!DOCTYPE Config
[
<!ENTITY includeddoc SYSTEM "specific-config.xml">
]
>

<Config
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="config.xsd">

...
...
...
<!--==================== Это ты вставляешь твой документ в том месте где надо =================== -->
&includeddoc;
...
...
...

</Config>

Добавлено: 05 мар 2007, 15:39
sz
Ужос-ужос-ужос.
И зачем люди мучают себя и процессор хмлем?

Добавлено: 05 мар 2007, 15:40
vg
Demurrage писал(а):This approach has failed with the same error, unable to locate the xml doc to include i.e. specific-config.xml. Once again, the the doc to include was being looked for in the folder the JVM was executed in and not from the Jar, where the original xml doc resides.
vg писал(а):Если тебе надо вставить в документ другой документ, то делается просто

<?xml version="1.0"?>

<!DOCTYPE Config
[
<!ENTITY includeddoc SYSTEM "specific-config.xml">
]
>

<Config
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="config.xsd">

...
...
...
<!--==================== Это ты вставляешь твой документ в том месте где надо =================== -->
&includeddoc;
...
...
...

</Config>
Sorry, but
Зыс апроач не может хаз файлд, бекоз напиши в нотепад и посмотри браузером.

Добавлено: 05 мар 2007, 15:46
vg
Demurrage писал(а):This approach has failed with the same error, unable to locate the xml doc to include i.e. specific-config.xml. Once again, the the doc to include was being looked for in the folder the JVM was executed in and not from the Jar, where the original xml doc resides.
vg писал(а):Если тебе надо вставить в документ другой документ, то делается просто

<?xml version="1.0"?>

<!DOCTYPE Config
[
<!ENTITY includeddoc SYSTEM "specific-config.xml">
]
>

<Config
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="config.xsd">

...
...
...
<!--==================== Это ты вставляешь твой документ в том месте где надо =================== -->
&includeddoc;
...
...
...

</Config>
Забыл сказать. Ты эта ... про абсолютный путь слухал/ла ?

Добавлено: 05 мар 2007, 16:01
Demurrage
Perhaps, you've missed the point of my original post where I was talking about accessing the docs residing not on the file system, but in the jar instead. Just to clarify: there is no problem with your approach when files reside outside of the jar. However, the problem does persist if both docs are part of the jar, so you might want to use your own suggestion and give it a try.

The issue is resolved BTW. Basically, the idea was to feed the parse an input source and not input stream,
because the latter allows to specify a system id of the doc
i.e. the url to the file which makes the parser "understand" what the base URL is.

URL url = MyClass.class.getClassLoader().getResource("folder_in_jar/x.xml");
InputStream inputStream = url.openStream();
InputStreamReader isr = new InputStreamReader(inputStream, "UTF-8");
//setting systemID is crucial
//i.e. jar e.g. file:\\c:\myjar.jar!\folder_in_jar\x.xml
String systemId = url.getProtocol() + ":" + url.getPath();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setXIncludeAware(true);
DocumentBuilder documentBuilder = factory.newDocumentBuilder();
InputSource inputSource = new InputSource();
inputSource.setCharacterStream(isr);
//the part which does he trick
inputSource.setSystemId(systemId);
Document document = documentBuilder.parse(inputSource);

Do apprecite everyone's help.

vg писал(а):
Demurrage писал(а):This approach has failed with the same error, unable to locate the xml doc to include i.e. specific-config.xml. Once again, the the doc to include was being looked for in the folder the JVM was executed in and not from the Jar, where the original xml doc resides.
vg писал(а):Если тебе надо вставить в документ другой документ, то делается просто

<?xml version="1.0"?>

<!DOCTYPE Config
[
<!ENTITY includeddoc SYSTEM "specific-config.xml">
]
>

<Config
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="config.xsd">

...
...
...
<!--==================== Это ты вставляешь твой документ в том месте где надо =================== -->
&includeddoc;
...
...
...

</Config>
Sorry, but
Зыс апроач не может хаз файлд, бекоз напиши в нотепад и посмотри браузером.

Добавлено: 05 мар 2007, 16:10
Marmot
Demurrage писал(а): URL url = MyClass.class.getClassLoader().getResource("folder_in_jar/x.xml");
InputStream inputStream = url.openStream();
InputStreamReader isr = new InputStreamReader(inputStream, "UTF-8");
//setting systemID is crucial
//i.e. jar e.g. file:\\c:\myjar.jar!\folder_in_jar\x.xml
String systemId = url.getProtocol() + ":" + url.getPath();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setXIncludeAware(true);
DocumentBuilder documentBuilder = factory.newDocumentBuilder();
InputSource inputSource = new InputSource();
inputSource.setCharacterStream(isr);
//the part which does he trick
inputSource.setSystemId(systemId);
Document document = documentBuilder.parse(inputSource);
OMFG!!!!

Век живи, век учись... спасибо, теперь будем знать :)

Добавлено: 05 мар 2007, 16:16
Marmot
sz писал(а):Ужос-ужос-ужос.
И зачем люди мучают себя и процессор хмлем?
Ты, Зотин, не понимаешь души современного enterprise development-a :)
Процессор должен работать, a девелопер читать доки :)
Ну и что, что самому написать будет в 10 раз быстрее, менеджер такого не оценит :)

PS А когда-то и я был большим фаном XML-a :)