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

Все, что вы хотели знать о программизме, но боялись спросить.
Ответить
Аватара пользователя
Demurrage
Завсегдатай
Сообщения: 248
Зарегистрирован: 16 янв 2007, 12:47

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

Сообщение 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 :-)
Аватара пользователя
Ranger
Маньяк
Сообщения: 1199
Зарегистрирован: 22 окт 2003, 18:28
Откуда: 2:5025 -> Burnaby

Сообщение Ranger »

по-русски хоть можно отвечать или только на собачьей мове? ;)

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

P.S. кстати, Xinclude - это ни в коем случае не "processing instruction" :wink:
Аватара пользователя
Demurrage
Завсегдатай
Сообщения: 248
Зарегистрирован: 16 янв 2007, 12:47

Сообщение Demurrage »

Спасибо попробую.
Аватара пользователя
Earl Grey
Маньяк
Сообщения: 2893
Зарегистрирован: 22 фев 2005, 15:07

Сообщение Earl Grey »

А почему вы не можете просто читать реальный XML document; превращать его в XML node и реально вставлять его (не ссылку) в другой документ?
Аватара пользователя
Marmot
Графоман
Сообщения: 39279
Зарегистрирован: 17 фев 2003, 17:58
Откуда: Caulfeild
Контактная информация:

Сообщение Marmot »

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

Сообщение 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>
Аватара пользователя
Demurrage
Завсегдатай
Сообщения: 248
Зарегистрирован: 16 янв 2007, 12:47

Сообщение 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>
Аватара пользователя
sz
Маньяк
Сообщения: 1266
Зарегистрирован: 17 фев 2003, 19:34

Сообщение sz »

Ужос-ужос-ужос.
И зачем люди мучают себя и процессор хмлем?
vg
Маньяк
Сообщения: 2803
Зарегистрирован: 29 май 2003, 22:29
Откуда: Магадан - Миссиссага

Сообщение 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
Зыс апроач не может хаз файлд, бекоз напиши в нотепад и посмотри браузером.
vg
Маньяк
Сообщения: 2803
Зарегистрирован: 29 май 2003, 22:29
Откуда: Магадан - Миссиссага

Сообщение 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>
Забыл сказать. Ты эта ... про абсолютный путь слухал/ла ?
Аватара пользователя
Demurrage
Завсегдатай
Сообщения: 248
Зарегистрирован: 16 янв 2007, 12:47

Сообщение 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
Зыс апроач не может хаз файлд, бекоз напиши в нотепад и посмотри браузером.
Аватара пользователя
Marmot
Графоман
Сообщения: 39279
Зарегистрирован: 17 фев 2003, 17:58
Откуда: Caulfeild
Контактная информация:

Сообщение 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!!!!

Век живи, век учись... спасибо, теперь будем знать :)
Аватара пользователя
Marmot
Графоман
Сообщения: 39279
Зарегистрирован: 17 фев 2003, 17:58
Откуда: Caulfeild
Контактная информация:

Сообщение Marmot »

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

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