Xmllint using XSD+XMLCatalog cannot find uri - validation

I am trying to use xmllint with an XSD file that uses one xs:import without the #schemaLocation attrib set. (In OxygenXMLEditor this setup is working fine)
XSD relevant section:
...
<!-- this one is the trouble -->
<xs:import namespace="http://www.w3.org/1999/xhtml" />
<!-- this one is resolved fine -->
<xs:import namespace="http://www.idpf.org/2007/ops" schemaLocation="conf/b.xsd"/>
...
Given this XML Catalog file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE catalog PUBLIC "-//OASIS//DTD XML Catalogs V1.1//EN" "http://www.oasis-open.org/committees/entity/release/1.1/catalog.dtd">
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog">
<uri name="http://www.w3.org/1999/xhtml" uri="file:///home/me/code/base5html.xsd"/>
</catalog>
Ok, then I run it:
$ export XML_CATALOG_FILES=~/code/mycatalog.xml
$ export XML_DEBUG_CATALOG=1
$ xmllint --load-trace --noout --schema myschema.xsd test_doc.xml
Result (approx):
Loaded URL="myschema.xsd" ID="(null)"
Loaded URL="conf/b.xsd" ID="(null)"
Loaded URL="c.xsd" ID="(null)"
c.xsd:17: element element: Schemas parser error : Element '{http://www.w3.org/2001/XMLSchema}element', attribute 'ref': The QName value '{http://www.w3.org/1999/xhtml}p' does not resolve to a(n) element declaration.
c.xsd:18: element element: Schemas parser error : Element '{http://www.w3.org/2001/XMLSchema}element', attribute 'ref': The QName value '{http://www.w3.org/1999/xhtml}cite' does not resolve to a(n) element declaration.
c.xsd:26: element attributeGroup: Schemas parser error : Element '{http://www.w3.org/2001/XMLSchema}attributeGroup', attribute 'ref': The QName value '{http://www.w3.org/1999/xhtml}normAttrGrp' does not resolve to a(n) attribute group definition.
...
(more taken out)
...
WXS schema public/ctrl/lov.xsd failed to compile
Loaded URL="myschema.xml" ID="(null)"
Q: Isn't XSD+XMLCat a supported feature in libxml2 ?
( No hints to be found anywhere on the homepage : http://xmlsoft.org/catalog.html )

Related

Undefined namespace prefix error when using xlink

i have this xml :
<figure>
<objetmedia>
<image typeimage="figure" xlink:actuate="onLoad" xlink:href="picture-02.jpg" xlink:show="embed" xlink:type="simple"/>
</objetmedia>
</figure>
And i have this xsl script :
<xsl:template match="figure">
<figure>
<xsl:apply-templates select="objetmedia" mode="image"/>
</figure>
</xsl:template>
<xsl:template match="objetmedia" mode="image">
<img src='{image/#xlink:href}' />
</xsl:template>
But i have this error :
Warning: XSLTProcessor::transformToXml(): Undefined namespace prefix
Warning: XSLTProcessor::transformToXml(): xmlXPathCompiledEval:
evaluation failed Warning: XSLTProcessor::transformToXml(): runtime
error: file script.xsl line 154 element img Warning:
XSLTProcessor::transformToXml(): Internal error: Failed to evaluate
the AVT of attribute 'src'.
Why ?
You need to declare the xlink: namespace prefix in your stylesheet, and bind it to the same namespace uri as the original document uses. You haven't shown the part of your input document that includes the namespace declaration, but if it's the standard XLink namespace then you'd need to add
xmlns:xlink="http://www.w3.org/1999/xlink"
to an appropriate place, usually your xsl:stylesheet tag.
The point is that XPath expressions and match patterns use the prefix bindings of the stylesheet, not of the input xml document. What matters for the matching is the namespace uri and the local name. Your stylesheet could equally well declare xmlns:x="http://www.w3.org/1999/xlink" and then look for #x:href - as long as the namespaces match it'll find the right thing.

Mule expression in logger component not valid xpath

I have an xml like this:
<order>
<orderheader>
<orderissuedate>1/11/2013</orderissuedate>
</orderheader>
</order>
in the mule logger component set with INFO, i have a mule expression that tries to print out the orderissuedate 1/11/2013.
i use the expression:
[xpath('/order/orderheader//orderissuedate')] which didn't work.
i also tried: #[xpath('/order/orderheader/orderissuedate/text()').text] that didnt work also.
can someone tell me what the correct xpath expression is. i get this error message:
java.lang.RuntimeException: org.mule.api.MuleRuntimeException: Failed to evaluate XPath expression: "/Order/OrderHeader/OrderIssueDate/text()"
I've tested these xpath expressions using online xpath checkers, and they seem to work. thanks for your help.
Here is the original xml:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE Order>
<Order
xmlns:core="rrn:org.xcbl:schemas/xcbl/v4_0/core/core.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<OrderHeader>
<OrderNumber>
<BuyerOrderNumber>111111</BuyerOrderNumber>
</OrderNumber>
<OrderIssueDate>2013-06-28T08:40:12</OrderIssueDate>
<OrderReferences>
<AccountCode>
<core:RefNum></core:RefNum>
</AccountCode>
</OrderReferences>
</OrderHeader>
</Order>
and the error output from mule:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
java.lang.RuntimeException: org.mule.api.MuleRuntimeException: Failed to evaluate XPath expression: "/OrderIssueDate"
at org.mule.module.xml.el.XPathFunction.call(XPathFunction.java:50)
at org.mule.el.mvel.MVELFunctionAdaptor.call(MVELFunctionAdaptor.java:38)
at org.mvel2.optimizers.impl.refl.ReflectiveAccessorOptimizer.getMethod(ReflectiveAccessorOptimizer.java:1011)
at org.mvel2.optimizers.impl.refl.ReflectiveAccessorOptimizer.getMethod(ReflectiveAccessorOptimizer.java:987)
at org.mvel2.optimizers.impl.refl.ReflectiveAccessorOptimizer.compileGetChain(ReflectiveAccessorOptimizer.java:377)
at org.mvel2.optimizers.impl.refl.ReflectiveAccessorOptimizer.optimizeAccessor(ReflectiveAccessorOptimizer.java:143)
at org.mvel2.ast.ASTNode.optimize(ASTNode.java:159)
at org.mvel2.ast.ASTNode.getReducedValueAccelerated(ASTNode.java:115)
at org.mvel2.MVELRuntime.execute(MVELRuntime.java:85)
at org.mvel2.compiler.CompiledExpression.getDirectValue(CompiledExpression.java:123)
at org.mvel2.compiler.CompiledExpression.getValue(CompiledExpression.java:119)
at org.mvel2.compiler.CompiledExpression.getValue(CompiledExpression.java:113)
at org.mvel2.MVEL.executeExpression(MVEL.java:942)
at org.mule.el.mvel.MVELExpressionExecutor.execute(MVELExpressionExecutor.java:50)
at org.mule.el.mvel.MVELExpressionLanguage.evaluateInternal(MVELExpressionLanguage.java:214)
at org.mule.el.mvel.MVELExpressionLanguage.evaluate(MVELExpressionLanguage.java:163)
at org.mule.el.mvel.MVELExpressionLanguage.evaluate(MVELExpressionLanguage.java:142)
at org.mule.expression.DefaultExpressionManager.evaluate(DefaultExpressionManager.java:220)
at org.mule.expression.DefaultExpressionManager$2.match(DefaultExpressionManager.java:481)
at org.mule.util.TemplateParser.parse(TemplateParser.java:153)
at org.mule.util.TemplateParser.parse(TemplateParser.java:130)
at org.mule.expression.DefaultExpressionManager.parse(DefaultExpressionManager.java:477)
at org.mule.expression.DefaultExpressionManager.parse(DefaultExpressionManager.java:436)
at org.mule.api.processor.LoggerMessageProcessor.log(LoggerMessageProcessor.java:89)
at org.mule.api.processor.LoggerMessageProcessor.process(LoggerMessageProcessor.java:71)
at org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor.execute(ExceptionToMessagingExceptionExecutionInterceptor.java:27)
at org.mule.execution.MessageProcessorNotificationExecutionInterceptor.execute(MessageProcessorNotificationExecutionInterceptor.java:61)
at org.mule.execution.MessageProcessorExecutionTemplate.execute(MessageProcessorExecutionTemplate.java:47)
at org.mule.processor.chain.DefaultMessageProcessorChain.doProcess(DefaultMessageProcessorChain.java:95)
at org.mule.processor.chain.AbstractMessageProcessorChain.process(AbstractMessageProcessorChain.java:70)
at org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor.execute(ExceptionToMessagingExceptionExecutionInterceptor.java:27)
at org.mule.execution.MessageProcessorExecutionTemplate.execute(MessageProcessorExecutionTemplate.java:47)
at org.mule.processor.AbstractInterceptingMessageProcessorBase.processNext(AbstractInterceptingMessageProcessorBase.java:106)
at com.mulesoft.mule.module.datamapper.processors.DataMapperMessageProcessor.process(DataMapperMessageProcessor.java:132)
at org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor.execute(ExceptionToMessagingExceptionExecutionInterceptor.java:27)
at org.mule.execution.MessageProcessorNotificationExecutionInterceptor.execute(MessageProcessorNotificationExecutionInterceptor.java:61)
at org.mule.execution.MessageProcessorExecutionTemplate.execute(MessageProcessorExecutionTemplate.java:47)
at org.mule.processor.AbstractInterceptingMessageProcessorBase.processNext(AbstractInterceptingMessageProcessorBase.java:106)
at org.mule.interceptor.AbstractEnvelopeInterceptor.process(AbstractEnvelopeInterceptor.java:55)
at org.mule.processor.AsyncInterceptingMessageProcessor.processNextTimed(AsyncInterceptingMessageProcessor.java:122)
at org.mule.processor.AsyncInterceptingMessageProcessor$AsyncMessageProcessorWorker$1.process(AsyncInterceptingMessageProcessor.java:192)
at org.mule.processor.AsyncInterceptingMessageProcessor$AsyncMessageProcessorWorker$1.process(AsyncInterceptingMessageProcessor.java:185)
at org.mule.execution.ExecuteCallbackInterceptor.execute(ExecuteCallbackInterceptor.java:20)
at org.mule.execution.HandleExceptionInterceptor.execute(HandleExceptionInterceptor.java:34)
at org.mule.execution.HandleExceptionInterceptor.execute(HandleExceptionInterceptor.java:18)
at org.mule.execution.BeginAndResolveTransactionInterceptor.execute(BeginAndResolveTransactionInterceptor.java:58)
at org.mule.execution.ResolvePreviousTransactionInterceptor.execute(ResolvePreviousTransactionInterceptor.java:48)
at org.mule.execution.SuspendXaTransactionInterceptor.execute(SuspendXaTransactionInterceptor.java:54)
at org.mule.execution.ValidateTransactionalStateInterceptor.execute(ValidateTransactionalStateInterceptor.java:44)
at org.mule.execution.IsolateCurrentTransactionInterceptor.execute(IsolateCurrentTransactionInterceptor.java:44)
at org.mule.execution.ExternalTransactionInterceptor.execute(ExternalTransactionInterceptor.java:52)
at org.mule.execution.RethrowExceptionInterceptor.execute(RethrowExceptionInterceptor.java:32)
at org.mule.execution.RethrowExceptionInterceptor.execute(RethrowExceptionInterceptor.java:17)
at org.mule.execution.TransactionalErrorHandlingExecutionTemplate.execute(TransactionalErrorHandlingExecutionTemplate.java:113)
at org.mule.execution.TransactionalErrorHandlingExecutionTemplate.execute(TransactionalErrorHandlingExecutionTemplate.java:34)
at org.mule.processor.AsyncInterceptingMessageProcessor$AsyncMessageProcessorWorker.doRun(AsyncInterceptingMessageProcessor.java:184)
at org.mule.work.AbstractMuleEventWork.run(AbstractMuleEventWork.java:43)
at org.mule.work.WorkerContext.run(WorkerContext.java:311)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.mule.api.MuleRuntimeException: Failed to evaluate XPath expression: "/OrderIssueDate"
at org.mule.module.xml.expression.AbstractXPathExpressionEvaluator.evaluate(AbstractXPathExpressionEvaluator.java:144)
at org.mule.expression.DefaultExpressionManager.evaluate(DefaultExpressionManager.java:311)
at org.mule.expression.DefaultExpressionManager.evaluate(DefaultExpressionManager.java:230)
at org.mule.expression.DefaultExpressionManager.evaluate(DefaultExpressionManager.java:186)
at org.mule.module.xml.el.XPathFunction.call(XPathFunction.java:43)
... 60 more
Caused by: org.mule.api.transformer.TransformerException: Could not find a transformer to transform "SimpleDataType{type=java.util.LinkedHashMap, mimeType='*/*'}" to "SimpleDataType{type=org.dom4j.Document, mimeType='*/*'}".
at org.mule.registry.MuleRegistryHelper.lookupTransformer(MuleRegistryHelper.java:252)
at org.mule.DefaultMuleMessage.getPayload(DefaultMuleMessage.java:355)
at org.mule.DefaultMuleMessage.getPayload(DefaultMuleMessage.java:313)
at org.mule.module.xml.expression.AbstractXPathExpressionEvaluator.getPayloadForXPath(AbstractXPathExpressionEvaluator.java:154)
at org.mule.module.xml.expression.AbstractXPathExpressionEvaluator.evaluate(AbstractXPathExpressionEvaluator.java:115)
... 64 more
ERROR 2013-08-26 00:40:49,893 [[mule_egc2].EGC_FlowFlow1.stage1.02] org.mule.exception.DefaultMessagingExceptionStrategy:
********************************************************************************
Message : Could not find a transformer to transform "SimpleDataType{type=java.util.LinkedHashMap, mimeType='*/*'}" to "SimpleDataType{type=org.dom4j.Document, mimeType='*/*'}".
Code : MULE_ERROR-236
--------------------------------------------------------------------------------
Exception stack is:
1. Could not find a transformer to transform "SimpleDataType{type=java.util.LinkedHashMap, mimeType='*/*'}" to "SimpleDataType{type=org.dom4j.Document, mimeType='*/*'}". (org.mule.api.transformer.TransformerException)
org.mule.registry.MuleRegistryHelper:252 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/transformer/TransformerException.html)
--------------------------------------------------------------------------------
Root Exception stack trace:
org.mule.api.transformer.TransformerException: Could not find a transformer to transform "SimpleDataType{type=java.util.LinkedHashMap, mimeType='*/*'}" to "SimpleDataType{type=org.dom4j.Document, mimeType='*/*'}".
at org.mule.registry.MuleRegistryHelper.lookupTransformer(MuleRegistryHelper.java:252)
at org.mule.DefaultMuleMessage.getPayload(DefaultMuleMessage.java:355)
at org.mule.DefaultMuleMessage.getPayload(DefaultMuleMessage.java:313)
+ 3 more (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
********************************************************************************
Use this:
<logger message="OrderIssueDate is #[xpath('//Order/OrderHeader/OrderIssueDate').text]" level="INFO" />
Make sure that to use the case correctly for your XML elements hierarchy. You have order in top XML while Order in lower one and so on
the xpath expression that would work according to me is #[xpath://orderissuedate] To print using the logger you should use something like <logger message="#[xpath://orderissuedate]" level="INFO"/>
From the conversation on one of the answers the following solutions hould work.
<logger message="Value of Order Issue Date #[xpath('//OrderIssueDate').text]" level="INFO" />
It would be better if the DTD of the Order is also provided.
Your original XML seems to have namespace :-
xmlns:core="rrn:org.xcbl:schemas/xcbl/v4_0/core/core.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
So, if you need to extract the value using Xpath from your original XML, you need Mule namespace manger :- https://developer.mulesoft.com/docs/display/current/XML+Namespaces
Other than that if you want to extract the value from your XML you shown above, you can use the Mules latest Xpath3 available right now from Mule version 3.6 which is easy to use :- https://developer.mulesoft.com/docs/display/current/XPath
Hope it helps you :)
You can use the mule latest xpath3 like this if you are getting namespaces
[xpath3('//*:orderissuedate/text()')]
Try this, it may help:
#[xpath3('//order/orderheader/orderissuedate/text()')]

Get value of XML attribute with namespace

I'm parsing a pptx file and ran into an issue. This is a sample of the source XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<p:presentation xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<p:sldMasterIdLst>
<p:sldMasterId id="2147483648" r:id="rId2"/>
</p:sldMasterIdLst>
<p:sldIdLst>
<p:sldId id="256" r:id="rId3"/>
</p:sldIdLst>
<p:sldSz cx="10080625" cy="7559675"/>
<p:notesSz cx="7772400" cy="10058400"/>
</p:presentation>
I need to to get the r:id attribute value in the sldMasterId tag.
doc = Nokogiri::XML(path_to_pptx)
doc.xpath('p:presentation/p:sldMasterIdLst/p:sldMasterId').attr('id').value
returns 2147483648 but I need rId2, which is the r:id attribute value.
I found the attribute_with_ns(name, namespace) method, but
doc.xpath('p:presentation/p:sldMasterIdLst/p:sldMasterId').attribute_with_ns('id', 'r')
returns nil.
You can reference the namespace of attributes in your xpath the same way you reference element namespaces:
doc.xpath('p:presentation/p:sldMasterIdLst/p:sldMasterId/#r:id')
If you want to use attribute_with_ns, you need to use the actual namespace, not just the prefix:
doc.at_xpath('p:presentation/p:sldMasterIdLst/p:sldMasterId')
.attribute_with_ns('id', "http://schemas.openxmlformats.org/officeDocument/2006/relationships")
http://nokogiri.org/Nokogiri/XML/Node.html#method-i-attributes
If you need to distinguish attributes with the same name, with different namespaces use attribute_nodes instead.
doc.xpath('p:presentation/p:sldMasterIdLst/p:sldMasterId').each do |element|
element.attribute_nodes().select do |node|
puts node if node.namespace && node.namespace.prefix == "r"
end
end

Read an XML node value using Linq

I have what should be a fairly simple requirement.
I want to use LINQ to XML in a VS2010 project to get the following node values:
GPO->Name
GPO->LinksTo->SOMName
GPO->LinksTo->SOMPath
Then:
If GPO->User->ExtensionDataCount node exists, I want to return count of all child nodes
Likewise:
If GPO->Computer->ExtensionData exists, return count of all child nodes
here is the XML, those of you familiar with Group Policy exports will have seen this before:
<?xml version="1.0" encoding="utf-16"?>
<GPO xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.microsoft.com/GroupPolicy/Settings">
<Identifier>
<Domain xmlns="http://www.microsoft.com/GroupPolicy/Types">our.domain.fqdn</Domain>
</Identifier>
<Name>The Name I want to get</Name>
<Computer>
<VersionDirectory>1</VersionDirectory>
<VersionSysvol>1</VersionSysvol>
<Enabled>true</Enabled>
</Computer>
<User>
<VersionDirectory>4</VersionDirectory>
<VersionSysvol>4</VersionSysvol>
<Enabled>true</Enabled>
<ExtensionData>
<Extension xmlns:q1="http://www.microsoft.com/GroupPolicy/Settings/Scripts" xsi:type="q1:Scripts">
<q1:Script>
<q1:Command>Logon.cmd</q1:Command>
<q1:Type>Logon</q1:Type>
<q1:Order>0</q1:Order>
<q1:RunOrder>PSNotConfigured</q1:RunOrder>
</q1:Script>
</Extension>
<Name>Scripts</Name>
</ExtensionData>
</User>
<LinksTo>
<SOMName>an interesting data value</SOMName>
<SOMPath>some data value</SOMPath>
<Enabled>true</Enabled>
<NoOverride>false</NoOverride>
</LinksTo>
</GPO>
I have loaded the XML file into an XDocument, then tried to pull the Name value with:
XDoc.Elements("Name").FirstOrDefault.Value
XDoc.Descendants("Name").First().Value
But I'm getting errors: Object reference not set to an instance of an object and then: Sequence contains no elements.
I'm guessing I might have the path wrong, but I thought Descendants didn't require an exact path..
Where am I going wrong?
You have to use the declared namespace:
XNamespace ns = "http://www.microsoft.com/GroupPolicy/Settings";
var firstName = xdoc.Descendants(ns + "Name").First().Value;

Get Nokogiri to not add "default" namespace when adding nodes

Background:
I want to take some xml from one file, put it in a template file and then save the modified template as a new file. It works, but when I save the file out, all the nodes that I added have a default namespace prepeneded, i.e.
<default:ComponentRef Id="C__AD1817F9C64A42F0A14DDDDC82DFC8D9"/>
<default:ComponentRef Id="C__157DD41D70854617A3D6D1E4A39B589F"/>
<default:ComponentRef Id="C__2E6D8662F38FE62CAFA9F8842A28F510"/>
<default:ComponentRef Id="C__54E5E2181323D4A5F37293DAA87B4230"/>
Which I want to be just:
<ComponentRef Id="C__AD1817F9C64A42F0A14DDDDC82DFC8D9"/>
<ComponentRef Id="C__157DD41D70854617A3D6D1E4A39B589F"/>
<ComponentRef Id="C__2E6D8662F38FE62CAFA9F8842A28F510"/>
<ComponentRef Id="C__54E5E2181323D4A5F37293DAA87B4230"/>
The following is my ruby code:
file = "wixmain/generated/DarkOutput.wxs"
template = "wixmain/generated/MsiComponentTemplate.wxs"
output = "wixmain/generated/MSIComponents.wxs"
dark_output = Nokogiri::XML(File.open(file))
template_file = Nokogiri::XML(File.open(template))
#get stuff from dark output
components = dark_output.at_css("Directory[Id='TARGETDIR']")
component_ref = dark_output.at_css("Feature[Id='DefaultFeature']")
#where to insert in template doc
template_component_insert_point = template_file.at_css("DirectoryRef[Id='InstallDir']")
template_ref_insert_point = template_file.at_css("ComponentGroup[Id='MSIComponentGroup']")
template_component_insert_point.children= components.children()
template_ref_insert_point.children= component_ref.children()
#write out filled template to output file
File.open(output, 'w') { |f| template_file.write_xml_to f }
Update
Example of my template file:
<?xml version="1.0" encoding="utf-8"?>
<Wix xmlns='http://schemas.microsoft.com/wix/2006/wi'>
<Fragment>
<ComponentGroup Id='MSIComponentGroup'>
</ComponentGroup>
</Fragment>
<Fragment Id='MSIComponents'>
<DirectoryRef Id='InstallDir'>
</DirectoryRef>
</Fragment>
</Wix>
Workaround was to remove the xmlns attribute in the input file.
Or to use the remove_namespaces! method when opening the input file
input_file = Nokogiri::XML(File.open(input))
input_file.remove_namespaces!
I think you are missing a sample of the template file. Also, is the sample from the input complete?
Nokogiri is either finding the default: namespace during its parsing of one of the two files, and you are inheriting it, or maybe it is not happy with the sample during parsing and is unable to parse cleanly, and as a result somehow adding the default: namespace. You can check the emptiness of the errors array after parsing the dark_output and template_file to see if Nokogiri is happy.
dark_output = Nokogiri::XML(File.open(file))
template_file = Nokogiri::XML(File.open(template))
if (dark_output.errors.any? || template_file.errors.any?)
[... do something here ...]
end
For the fastest answer, you might want to take this question directly to the developers via the Nokogiri-Talk mail-list.

Resources