Подключить xml файл в xml
So currently I'm doing some XML-> XSLT-> (HTML5/CSS3) work. Right now I have a menu.xml file, and I'd like to include it in either the XSL file or the XML page. I've done lots of searching, but I'm unable to find a straightforward answer.
So, how do I include an XML file in to another XML file or in to a XSL file?
Edit: By include, I mean referencing/loading it from another file, not copy and pasting it or simply embedding it.
By 'include' it, do you mean that you want to copy/paste the contents of menu.xml into another file and host it in there without problems, or do you mean that you want some way to remotely reference menu.xml from the host file, or do you mean that you want your web server to copy the contents of menu.xml into the host file before serving it, as though you had copy/pasted the contents yourself?
Ah, I kind of meant it like referencing it from the file, not including it. Damn my programming speak. I'm too use to C.
Good question, +1. See my answer for explanation and two complete code examples that answer your questions. :)
You could use an external (parsed) general entity.
You declare the entity like this:
Then you reference it like this:
A complete example:
When the XML parser reads the file, it will expand the entity reference and include the referenced XML file as part of the content.
If the "otherFile.xml" contained:
Then the XML would be evaluated and "seen" by an XML parser as:
A few references that might be helpful:
browsers may disable this for security reasons for local files. use --allow-file-access-from-files switch for chrome or upload to the host
The other answers cover the 2 most common approaches, Xinclude and XML external entities. Microsoft has a really great writeup on why one should prefer Xinclude, as well as several example implementations. I've quoted the comparison below:
It is a comparison between Xinclude and XML external entities, both of which are the top 2 answers and already show or provide use examples. I felt it added to the discussion and was too long/complicated for a comment. Likewise the question asks 'can' and not 'how', so as a far as answering a generalized question, this goes towards clarifying directionality which I felt was really the intent of the question. Lots of other good references on specific implementation. That being, said, thank you for the feedback. I'm updating it with an example shortly.
I appreciate your response and respect that you tried to resolve the issue by adding an example, but I think your answer is still fundamentally flawed. Generally, when quoting text from elsewhere, you should include that text in a blockquote (so that it's obvious you're not trying to plagiarize) and, more importantly, provide your own discussion above / below the blockquote that explains very clearly why you quoted that particular text and how it helps answer the question. If do both of those things and comment again (so I get notified) I will gladly delete my comment and retract my downvote.
seem to be independent XML and XSLT files. Don't they have to be linked? Or do you somehow put them into a same file? Otherwise, how does one file know how to suck in data from the other file?
I agree that some of the W3Schools pages, such as that one, are inadequate. They could have easily included mention of linking the stylesheet, as is done in XSLT - Transformation.
5 Answers 5
I. Here is how any XML document or fragment can be embedded in an XSLT stylesheet and used during the transformation:
When this transformation is applied on any XML document (not used in this example), the wanted result (just copying the XML) is produced:
Remember: Any XML can be embedded into an XSLT stylesheet, provided it is wrapped into a namespaced element (the namespace not the XSLT namespace) and this wrapping element is at the global level (a child of the (top) element).
II. Accessing the XML menu file that resides in a separate XML file:
To do this we have to change only slightly the previous example:
If the menu XML file is in the 'menu.XML' file (in the same directory as the XSLT stylesheet file, then this transformation produces exactly the same result as the previous:
Do note: In both cases we are using the standard XSLT function document()
Typically, one defines a global-level variable, whose value is the result of calling the document() function. Then this variable and its contents is accessed via XPath expressions during the transformation.
Думаю, для многих не секрет, что xml является достаточно удобным способом хранения и передачи информации. Вот уже который раз натыкаюсь в литературе на утверждение, что в будущем xml должен заменить html, а появление xhtml является тому подтверждением. Но тут есть нюанс. все браузеры знают как отображать html-документы, но ни один из них не знает, как должны отображаться xml-документы. Это связано прежде всего с тем, что формируя xml-документ Вы можете ввести свои теги. Я хочу коротко (это очень большая тема, на самом деле) рассказать о так называемых «Таблицах преобразований xml-документов».
Думаю, что многие наверняка знакомы с ними, но надеюсь что кому-то это может быть полезно, а, учитывая мою любовь к практике, хочу показать всё на очень простом примере
Что мы имеем
Если мы попробуем просмотреть его в браузере, то увидим нечто подобное:
Существует несколько способов визуализировать содержимое этого документа.
К нему можно подключить обычную таблицу стилей (css-файл) или таблицу преобразований.
Таблица преобразований представляет из себя xml-документ, оформленный по определённым правилам и имеющий расширение .xslt.
Допустим нам нужно отобразить информацию, содержащуюся в xml-документе, для этого создадим таблицу преобразований (файл будет называться style.xslt):
Подключить таблицу преобразований (к исходному xml-документу конечно же) можно следующим образом:
В итоге, открыв тот же самый файл в браузере мы увидим следующее:
В двух словах, как это работает
В таблице преобразований описаны три шаблона: document, items и item. Когда в шаблоне встречается элемент xsl:apply-templates на его место подставляются то, что получится в результате обработки всех элементов, удовлетворяющих выражению select (я указывал просто названия тегов, хотя там могут быть достаточно сложные конструкции). Аналогично вставляются значения тегов (тег xsl:value-of) и атрибуты для тегов (тег xsl:attribute).
Шаблон document формирует основу html-страницы (теги html, head, body), а в них подставляются заголовок страницы и список элементов, формирующийся по шаблону items (Элементы списка формируются по шаблону items).
Всё преобразование делается на стороне клиента.
Это лишь малая доля того, что может предоставить технология таблиц преобразований. Visual Studio имеет удобный интерфейс по работе с ними, в том числе просмотр сгенерированного html.
поэтому в настоящее время я делаю некоторую работу XML-> XSLT-> (HTML5/CSS3). Сейчас у меня есть меню.xml-файл, и я хотел бы включить его в файл XSL или на страницу XML. Я много искал, но не могу найти прямого ответа.
Итак, как включить XML-файл в другой XML-файл или в файл XSL?
Edit: под include я имею в виду ссылку/загрузку из другого файла, а не копирование и вставку или просто встраивание.
I. Вот как любой XML-документ или фрагмент может быть встроен в таблицу стилей XSLT и использоваться во время преобразования:
когда это преобразование применяется к любому XML-документу (не используется в этом примере), желаемый результат (просто копирование XML) создается:
помните: любой XML может быть встроен в таблицу стилей XSLT при условии, что он обернут в элемент пространства имен (пространство имен не пространство имен XSLT), и этот элемент обертывания находится на глобальном уровне (дочерний элемент (верхний) элемент).
II. Доступ к файлу меню XML, который находится в отдельном файле XML:
для этого нам нужно лишь немного изменить предыдущий пример:
если XML-файл меню находится в 'menu.XML' file (в том же каталоге, что и файл таблицы стилей XSLT, тогда это преобразование производит точно то же самое результат как и предыдущие:
обратите внимание: в обоих случаях мы используем стандартную функцию XSLT document()
обычно определяется переменная глобального уровня, значение которой является результатом вызова
Итак, как включить XML-файл в другой XML-файл или в файл XSL?
можно использовать внешняя сущность для справки .в XML file и включить содержимое в XML-файл или XSLT (или оба).
по include, я имею в виду ссылку / загрузку это из другого файла, а не копировать и вставить или просто вставить.
С помощью внешних сущности, вы можете ссылаться / загружать .в XML содержимое из внешних файлов и не нужно дублировать содержимое XML.
например, если вы хотите меню.xml-содержимое, включенное в XSLT, вы объявите внешнюю сущность в своем XSLT следующим образом:
и может затем ссылаться на него, как на любой другой объект:
когда XSLT проанализирован, ссылка на сущность будет развернута и содержимое XML меню.XML будет включен как часть документа XSLT, как если бы вы скопировали / вставили в место, где была ссылка на сущность.
Я блоге об этом. Вы используете document () для получения другого XML и передачи содержимого с помощью параметров.
I mean is there any import tag in XML that takes XML path as parameter and imports XML (for which path is provided).
4 Answers 4
You can add this after the xml declaration
this is to put into the XML (data) file? Is this the only way or can you also tell an XSLT file to get data from which XML file, or have a 3rd file that includes both an XML file with an XSLT file?
alternative could be to include the XML file into another XML file somehow that specifies the stylesheet, but not sure if this is straightforward (might need to specially author the XPaths etc.)
One file doesn't know to "suck in data" the other file, because the files aren't what will do the processing.
Some sort of XSLT processor will do this, and the way it will be told what to work on varies so it can handle different use cases.
In the case of rendering the entire transform of an XML document when it is displayed in a browser, then processing-instruction:
(Really it should have been "text/xml" for the type as that's the mime-type of an XSL document, but this was in the tail-end of the browser wars and browser feature implementation was still often happening faster than the speed of common-sense).
If you are controlling the transform programatically using a library of some sort (there are objects for client-side javascript and libraries in any language you're likely to want to do this from), then you've got enough control to detail what gets transformed by what. Some interesting cases here include.
You could even have a document with a node of content and a node of transforms, pick them out and run the transform.
If you are running the same transformation on multiple XML documents, it is very often more efficient to call some sort of "PreCompile()" method or similar, which takes a hit on that call to benefit all the subsequent transforms.
4 Answers 4
Читайте также: