Ошибка разбора xml ссылка на необъявленный префикс пространства имен

How do I solve the

Reference to undeclared namespace prefix: '%s'

problem with Microsoft’s msxml implementation?


I’m using an XML feed from a government web-site that contains values i need to parse. The xml contains namespaces:

<?xml version="1.0" encoding="ISO-8859-1"?>
<rdf:RDF
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns="http://purl.org/rss/1.0/"
    xmlns:cb="http://www.cbwiki.net/wiki/index.php/Specification_1.1"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:dcterms="http://purl.org/dc/terms/"
    xmlns:xsi="http://www.w3c.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.w3c.org/1999/02/22-rdf-syntax-ns#rdf.xsd">
    <item rdf:about="http://www.bankofcanada.ca/stats/rates_rss/STATIC_IEXE0101.xml">
        <cb:statistics>
            <cb:exchangeRate>
                <cb:value decimals="4">1.0351</cb:value>
                <cb:baseCurrency>CAD</cb:baseCurrency>
                <cb:targetCurrency>USD</cb:targetCurrency>
                <cb:rateType>Bank of Canada noon rate</cb:rateType>
                <cb:observationPeriod frequency="daily">2011-05-09T12:15:00-04:00</cb:observationPeriod>
            </cb:exchangeRate>
        </cb:statistics>
    </item>
</rdf:RDF>

Running the XPath query:

/rdf:RDF/item/cb:statistics/cb:exchangeRate/cb:targetCurrency

fails with the error:

Reference to undeclared namespace prefix: 'rdf'

Edit:

If i edit the original XML to remove all use of namespaces:

<?xml version="1.0" encoding="ISO-8859-1"?>
<rdf>
    <item>
        <statistics>
            <exchangeRate>
                <value decimals="4">1.0351</value>
                <baseCurrency>CAD</baseCurrency>
                <targetCurrency>USD</targetCurrency>
                <rateType>Bank of Canada noon rate</rateType>
                <observationPeriod frequency="daily">2011-05-09T12:15:00-04:00</observationPeriod>
            </exchangeRate>
        </statistics>
    </item>
</rdf>

The query /rdf/item/statistics/exchangeRate/baseCurrency doesn’t fail, and returns nodes:

<baseCurrency>CAD</baseCurrency>

How do i get Microsoft XML to work with namespaces?


Edit 2

i’ve tried adding SelectionNamespaces to the DOMDocument object:

doc.setProperty('SelectionNamespaces', 'xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:cb="http://www.cbwiki.net/wiki/index.php/Specification_1.1"');

Now the xpath query doesn’t fail, but it also returns no nodes:

nodes = doc.selectNodes('/rdf:RDF/item/cb:statistics/cb:exchangeRate/cb:targetCurrency');

See also

  • “undeclared reference to namespace prefix ” error
  • XMLReader — How to handle undeclared namespace
  • PRB: Specifying Fully Qualified Element Names in XPath Queries
  • XPath not working properly.

Перейти к контенту

How do I solve the

Reference to undeclared namespace prefix: '%s'

problem with Microsoft’s msxml implementation?


I’m using an XML feed from a government web-site that contains values i need to parse. The xml contains namespaces:

<?xml version="1.0" encoding="ISO-8859-1"?>
<rdf:RDF
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns="http://purl.org/rss/1.0/"
    xmlns:cb="http://www.cbwiki.net/wiki/index.php/Specification_1.1"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:dcterms="http://purl.org/dc/terms/"
    xmlns:xsi="http://www.w3c.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.w3c.org/1999/02/22-rdf-syntax-ns#rdf.xsd">
    <item rdf:about="http://www.bankofcanada.ca/stats/rates_rss/STATIC_IEXE0101.xml">
        <cb:statistics>
            <cb:exchangeRate>
                <cb:value decimals="4">1.0351</cb:value>
                <cb:baseCurrency>CAD</cb:baseCurrency>
                <cb:targetCurrency>USD</cb:targetCurrency>
                <cb:rateType>Bank of Canada noon rate</cb:rateType>
                <cb:observationPeriod frequency="daily">2011-05-09T12:15:00-04:00</cb:observationPeriod>
            </cb:exchangeRate>
        </cb:statistics>
    </item>
</rdf:RDF>

Running the XPath query:

/rdf:RDF/item/cb:statistics/cb:exchangeRate/cb:targetCurrency

fails with the error:

Reference to undeclared namespace prefix: 'rdf'

Edit:

If i edit the original XML to remove all use of namespaces:

<?xml version="1.0" encoding="ISO-8859-1"?>
<rdf>
    <item>
        <statistics>
            <exchangeRate>
                <value decimals="4">1.0351</value>
                <baseCurrency>CAD</baseCurrency>
                <targetCurrency>USD</targetCurrency>
                <rateType>Bank of Canada noon rate</rateType>
                <observationPeriod frequency="daily">2011-05-09T12:15:00-04:00</observationPeriod>
            </exchangeRate>
        </statistics>
    </item>
</rdf>

The query /rdf/item/statistics/exchangeRate/baseCurrency doesn’t fail, and returns nodes:

<baseCurrency>CAD</baseCurrency>

How do i get Microsoft XML to work with namespaces?


Edit 2

i’ve tried adding SelectionNamespaces to the DOMDocument object:

doc.setProperty('SelectionNamespaces', 'xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:cb="http://www.cbwiki.net/wiki/index.php/Specification_1.1"');

Now the xpath query doesn’t fail, but it also returns no nodes:

nodes = doc.selectNodes('/rdf:RDF/item/cb:statistics/cb:exchangeRate/cb:targetCurrency');

See also

  • “undeclared reference to namespace prefix ” error
  • XMLReader — How to handle undeclared namespace
  • PRB: Specifying Fully Qualified Element Names in XPath Queries
  • XPath not working properly.

How do I solve the

Reference to undeclared namespace prefix: '%s'

problem with Microsoft’s msxml implementation?


I’m using an XML feed from a government web-site that contains values i need to parse. The xml contains namespaces:

<?xml version="1.0" encoding="ISO-8859-1"?>
<rdf:RDF
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns="http://purl.org/rss/1.0/"
    xmlns:cb="http://www.cbwiki.net/wiki/index.php/Specification_1.1"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:dcterms="http://purl.org/dc/terms/"
    xmlns:xsi="http://www.w3c.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.w3c.org/1999/02/22-rdf-syntax-ns#rdf.xsd">
    <item rdf:about="http://www.bankofcanada.ca/stats/rates_rss/STATIC_IEXE0101.xml">
        <cb:statistics>
            <cb:exchangeRate>
                <cb:value decimals="4">1.0351</cb:value>
                <cb:baseCurrency>CAD</cb:baseCurrency>
                <cb:targetCurrency>USD</cb:targetCurrency>
                <cb:rateType>Bank of Canada noon rate</cb:rateType>
                <cb:observationPeriod frequency="daily">2011-05-09T12:15:00-04:00</cb:observationPeriod>
            </cb:exchangeRate>
        </cb:statistics>
    </item>
</rdf:RDF>

Running the XPath query:

/rdf:RDF/item/cb:statistics/cb:exchangeRate/cb:targetCurrency

fails with the error:

Reference to undeclared namespace prefix: 'rdf'

Edit:

If i edit the original XML to remove all use of namespaces:

<?xml version="1.0" encoding="ISO-8859-1"?>
<rdf>
    <item>
        <statistics>
            <exchangeRate>
                <value decimals="4">1.0351</value>
                <baseCurrency>CAD</baseCurrency>
                <targetCurrency>USD</targetCurrency>
                <rateType>Bank of Canada noon rate</rateType>
                <observationPeriod frequency="daily">2011-05-09T12:15:00-04:00</observationPeriod>
            </exchangeRate>
        </statistics>
    </item>
</rdf>

The query /rdf/item/statistics/exchangeRate/baseCurrency doesn’t fail, and returns nodes:

<baseCurrency>CAD</baseCurrency>

How do i get Microsoft XML to work with namespaces?


Edit 2

i’ve tried adding SelectionNamespaces to the DOMDocument object:

doc.setProperty('SelectionNamespaces', 'xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:cb="http://www.cbwiki.net/wiki/index.php/Specification_1.1"');

Now the xpath query doesn’t fail, but it also returns no nodes:

nodes = doc.selectNodes('/rdf:RDF/item/cb:statistics/cb:exchangeRate/cb:targetCurrency');

See also

  • “undeclared reference to namespace prefix ” error
  • XMLReader — How to handle undeclared namespace
  • PRB: Specifying Fully Qualified Element Names in XPath Queries
  • XPath not working properly.

Вопрос:

Пожалуйста помоги. После прочтения всех google и stackoverflow 🙂 мой мозг больше не работает.

У меня ниже TSQL (работает на SQL Server 2012)

Я не могу понять, где мне нужно объявить мое пространство имен:? И сколько пространств имен мне нужно объявить?

DECLARE @XML AS XML
DECLARE @hDoc AS INT

SELECT @XML = '<GetAssetWarrantyResponse xmlns="http://tempuri.org/">
<GetAssetWarrantyResult xmlns:a="http://schemas.datacontract.org/2004/07/Dell.AWR.Domain.Asset" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:Faults />
<a:Response>
<a:DellAsset>
<a:AssetParts i:nil="true" />
<a:CountryLookupCode>5252</a:CountryLookupCode>
<a:CustomerNumber>645651</a:CustomerNumber>
</a:DellAsset>
</a:Response>
</GetAssetWarrantyResult>
</GetAssetWarrantyResponse>'

EXEC sp_xml_preparedocument @hDoc OUTPUT, @XML

SELECT CountryLookupCode
FROM OPENXML(@hDoc, 'GetAssetWarrantyResponse/GetAssetWarrantyResult/a:Response/a:DellAsset')
WITH
(
CountryLookupCode   [nvarchar](20)  'a:CountryLookupCode'
)

EXEC sp_xml_removedocument @hDoc
GO

Лучший ответ:

Вы должны указать префиксы пространства имен при вызове sp_xml_preparedocument. В этом случае у вас есть a пространство имен и пространство имен по умолчанию (один без префикса: xmlns="...."):

EXEC sp_xml_preparedocument 
        @hDoc OUTPUT
        , @XML
        , '<root xmlns:d="http://tempuri.org/" xmlns:a="http://schemas.datacontract.org/2004/07/Dell.AWR.Domain.Asset"/>'

И правильно используйте зарегистрированные префиксы:

SELECT CountryLookupCode
FROM OPENXML(@hDoc, 'd:GetAssetWarrantyResponse/d:GetAssetWarrantyResult/a:Response/a:DellAsset')
WITH 
(
    CountryLookupCode   [nvarchar](20)  'a:CountryLookupCode'
)

Ответ №1

Я бы использовал встроенную встроенную поддержку XQuery в SQL Server:

DECLARE @XML AS XML

SELECT @XML = '<GetAssetWarrantyResponse xmlns="http://tempuri.org/">
<GetAssetWarrantyResult xmlns:a="http://schemas.datacontract.org/2004/07/Dell.AWR.Domain.Asset" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:Faults />
<a:Response>
<a:DellAsset>
<a:AssetParts i:nil="true" />
<a:CountryLookupCode>5252</a:CountryLookupCode>
<a:CustomerNumber>645651</a:CustomerNumber>
</a:DellAsset>
</a:Response>
</GetAssetWarrantyResult>
</GetAssetWarrantyResponse>'

;WITH XMLNAMESPACES(DEFAULT 'http://tempuri.org/', 'http://schemas.datacontract.org/2004/07/Dell.AWR.Domain.Asset' AS ns)
SELECT
@XML.value('(GetAssetWarrantyResponse/GetAssetWarrantyResult/ns:Response/ns:DellAsset/ns:CountryLookupCode)[1]', 'int')

В терминах пространств имен XML: вам необходимо определить все те, которые используются в вашем документе XML, до момента, когда вы хотите получить данные из

Please help. After reading all google and stackoverflow :) my brain does not work anymore.

I have below TSQL (running on SQL Server 2012)

I cannot figure out where I need to declare my a: namespace? And how many namespaces I need to declare?

DECLARE @XML AS XML
DECLARE @hDoc AS INT

SELECT @XML = '<GetAssetWarrantyResponse xmlns="http://tempuri.org/">
  <GetAssetWarrantyResult xmlns:a="http://schemas.datacontract.org/2004/07/Dell.AWR.Domain.Asset" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <a:Faults />
    <a:Response>
      <a:DellAsset>
        <a:AssetParts i:nil="true" />
        <a:CountryLookupCode>5252</a:CountryLookupCode>
        <a:CustomerNumber>645651</a:CustomerNumber>
      </a:DellAsset>
    </a:Response>
  </GetAssetWarrantyResult>
</GetAssetWarrantyResponse>'

EXEC sp_xml_preparedocument @hDoc OUTPUT, @XML

SELECT CountryLookupCode
FROM OPENXML(@hDoc, 'GetAssetWarrantyResponse/GetAssetWarrantyResult/a:Response/a:DellAsset')
WITH 
(
CountryLookupCode   [nvarchar](20)  'a:CountryLookupCode'
)

EXEC sp_xml_removedocument @hDoc
GO

marc_s's user avatar

marc_s

721k173 gold badges1320 silver badges1442 bronze badges

asked Apr 10, 2015 at 8:14

user188145's user avatar

You need to specify the namespace prefixes when invoking sp_xml_preparedocument. In this case you have the a namespace and the default namespace (the one without prefix: xmlns="....") :

EXEC sp_xml_preparedocument 
        @hDoc OUTPUT
        , @XML
        , '<root xmlns:d="http://tempuri.org/" xmlns:a="http://schemas.datacontract.org/2004/07/Dell.AWR.Domain.Asset"/>'

And use the registered prefixes properly :

SELECT CountryLookupCode
FROM OPENXML(@hDoc, 'd:GetAssetWarrantyResponse/d:GetAssetWarrantyResult/a:Response/a:DellAsset')
WITH 
(
    CountryLookupCode   [nvarchar](20)  'a:CountryLookupCode'
)

answered Apr 10, 2015 at 8:29

har07's user avatar

har07har07

87.6k12 gold badges81 silver badges132 bronze badges

4

I’d use the built-in, native XQuery support in SQL Server:

DECLARE @XML AS XML

SELECT @XML = '<GetAssetWarrantyResponse xmlns="http://tempuri.org/">
<GetAssetWarrantyResult xmlns:a="http://schemas.datacontract.org/2004/07/Dell.AWR.Domain.Asset" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:Faults />
<a:Response>
<a:DellAsset>
<a:AssetParts i:nil="true" />
<a:CountryLookupCode>5252</a:CountryLookupCode>
<a:CustomerNumber>645651</a:CustomerNumber>
</a:DellAsset>
</a:Response>
</GetAssetWarrantyResult>
</GetAssetWarrantyResponse>'

;WITH XMLNAMESPACES(DEFAULT 'http://tempuri.org/', 'http://schemas.datacontract.org/2004/07/Dell.AWR.Domain.Asset' AS ns)
SELECT
@XML.value('(GetAssetWarrantyResponse/GetAssetWarrantyResult/ns:Response/ns:DellAsset/ns:CountryLookupCode)[1]', 'int')

In terms of XML namespaces: you need to define all those used in your XML document up to the point where you want to get the data from

answered Apr 10, 2015 at 8:35

marc_s's user avatar

marc_smarc_s

721k173 gold badges1320 silver badges1442 bronze badges

0

Please help. After reading all google and stackoverflow :) my brain does not work anymore.

I have below TSQL (running on SQL Server 2012)

I cannot figure out where I need to declare my a: namespace? And how many namespaces I need to declare?

DECLARE @XML AS XML
DECLARE @hDoc AS INT

SELECT @XML = '<GetAssetWarrantyResponse xmlns="http://tempuri.org/">
<GetAssetWarrantyResult xmlns:a="http://schemas.datacontract.org/2004/07/Dell.AWR.Domain.Asset" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:Faults />
<a:Response>
<a:DellAsset>
<a:AssetParts i:nil="true" />
<a:CountryLookupCode>5252</a:CountryLookupCode>
<a:CustomerNumber>645651</a:CustomerNumber>
</a:DellAsset>
</a:Response>
</GetAssetWarrantyResult>
</GetAssetWarrantyResponse>'

EXEC sp_xml_preparedocument @hDoc OUTPUT, @XML

SELECT CountryLookupCode
FROM OPENXML(@hDoc, 'GetAssetWarrantyResponse/GetAssetWarrantyResult/a:Response/a:DellAsset')
WITH
(
CountryLookupCode   [nvarchar](20)  'a:CountryLookupCode'
)

EXEC sp_xml_removedocument @hDoc
GO

marc_s's user avatar

marc_s

721k173 gold badges1320 silver badges1442 bronze badges

asked Apr 10, 2015 at 8:14

user188145's user avatar

You need to specify the namespace prefixes when invoking sp_xml_preparedocument. In this case you have the a namespace and the default namespace (the one without prefix: xmlns="....") :

EXEC sp_xml_preparedocument 
        @hDoc OUTPUT
        , @XML
        , '<root xmlns:d="http://tempuri.org/" xmlns:a="http://schemas.datacontract.org/2004/07/Dell.AWR.Domain.Asset"/>'

And use the registered prefixes properly :

SELECT CountryLookupCode
FROM OPENXML(@hDoc, 'd:GetAssetWarrantyResponse/d:GetAssetWarrantyResult/a:Response/a:DellAsset')
WITH 
(
    CountryLookupCode   [nvarchar](20)  'a:CountryLookupCode'
)

answered Apr 10, 2015 at 8:29

har07's user avatar

har07har07

87.6k12 gold badges81 silver badges132 bronze badges

4

I’d use the built-in, native XQuery support in SQL Server:

DECLARE @XML AS XML

SELECT @XML = '<GetAssetWarrantyResponse xmlns="http://tempuri.org/">
<GetAssetWarrantyResult xmlns:a="http://schemas.datacontract.org/2004/07/Dell.AWR.Domain.Asset" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:Faults />
<a:Response>
<a:DellAsset>
<a:AssetParts i:nil="true" />
<a:CountryLookupCode>5252</a:CountryLookupCode>
<a:CustomerNumber>645651</a:CustomerNumber>
</a:DellAsset>
</a:Response>
</GetAssetWarrantyResult>
</GetAssetWarrantyResponse>'

;WITH XMLNAMESPACES(DEFAULT 'http://tempuri.org/', 'http://schemas.datacontract.org/2004/07/Dell.AWR.Domain.Asset' AS ns)
SELECT
@XML.value('(GetAssetWarrantyResponse/GetAssetWarrantyResult/ns:Response/ns:DellAsset/ns:CountryLookupCode)[1]', 'int')

In terms of XML namespaces: you need to define all those used in your XML document up to the point where you want to get the data from

answered Apr 10, 2015 at 8:35

marc_s's user avatar

marc_smarc_s

721k173 gold badges1320 silver badges1442 bronze badges

0

Я пытаюсь прочитать XML-файл

Я написал этот сценарий, но получаю сообщение об ошибке:

DECLARE @XML AS XML, @hDoc AS INT, @SQL NVARCHAR (MAX), @rootxmlns varchar(1000)    

SELECT @XML=CONVERT(XML, BulkColumn) 
FROM OPENROWSET(BULK 'F:__FilesDoneOutput202012231338562027.txt.xmi', SINGLE_BLOB) AS x;

SET @rootxmlns = '<root xmlns:soap="http://www.omg.org/XMI"/>'
EXEC sp_xml_preparedocument @hDoc OUTPUT, @XML, @rootxmlns

SELECT *
FROM OPENXML(@hDoc, 'Matrix:Customer')

Я проверил много ссылок, и все они предлагали использовать xmlns. Я пробовал многие из них, но все они не работают с одной и той же ошибкой.

Ошибка синтаксического анализа XML: ссылка на необъявленный префикс пространства имен: «Клиент».

Вот мой XMI

<?xml version="1.0" encoding="UTF-8"?>
<xmi:XMI xmlns:xmi="http://www.omg.org/XMI"
        xmlns:util="http:///org/apache/ctakes/typesystem/type/util.ecore"
        xmlns:tcas="http:///uima/tcas.ecore"
        xmlns:cas="http:///uima/cas.ecore"
        xmlns:type10="http:///org/cleartk/syntax/constituent/type.ecore"
        xmlns:ne="http:///org/cleartk/type/ne.ecore"
        xmlns:textsem="http:///org/apache/ctakes/typesystem/type/textsem.ecore"
        xmlns:types2="http:///org/apache/ctakes/assertion/zoner/types.ecore"
        xmlns:type6="http:///org/apache/ctakes/smokingstatus/i2b2/type.ecore"
        xmlns:refsem="http:///org/apache/ctakes/typesystem/type/refsem.ecore"
        xmlns:type11="http:///org/cleartk/syntax/dependency/type.ecore"
        xmlns:type="http:///de/tudarmstadt/ukp/dkpro/core/api/metadata/type.ecore"
        xmlns:type14="http:///org/cleartk/util/type.ecore"
        xmlns:assertion="http:///org/apache/ctakes/typesystem/type/temporary/assertion.ecore"
        xmlns:type8="http:///org/cleartk/score/type.ecore"
        xmlns:syntax="http:///org/apache/ctakes/typesystem/type/syntax.ecore"
        xmlns:type9="http:///org/cleartk/srl/type.ecore"
        xmlns:type2="http:///org/apache/ctakes/constituency/parser/uima/type.ecore"
        xmlns:types="http:///org/apache/ctakes/assertion/medfacts/types.ecore"
        xmlns:type7="http:///org/apache/ctakes/smokingstatus/type.ecore"
        xmlns:relation="http:///org/apache/ctakes/typesystem/type/relation.ecore"
        xmlns:type12="http:///org/cleartk/timeml/type.ecore"
        xmlns:type5="http:///org/apache/ctakes/sideeffect/type.ecore"
        xmlns:type15="http:///org/cleartk/ne/type.ecore"
        xmlns:type13="http:///org/cleartk/token/type.ecore"
        xmlns:structured="http:///org/apache/ctakes/typesystem/type/structured.ecore"
        xmlns:textspan="http:///org/apache/ctakes/typesystem/type/textspan.ecore"
        xmlns:libsvm="http:///org/apache/ctakes/smokingstatus/type/libsvm.ecore"
        xmlns:type3="http:///org/apache/ctakes/coreference/type.ecore"
        xmlns:type4="http:///org/apache/ctakes/drugner/type.ecore"
        xmi:version="2.0">
    <cas:NULL xmi:id="0"/>
    <tcas:DocumentAnnotation xmi:id="8"
                            sofa="1"
                            begin="0"
                            end="16975"
                            language="x-unspecified"/>
    <structured:DocumentID xmi:id="13"
                            documentID="1"/>
    <structured:DocumentIdPrefix xmi:id="15"
                                documentIdPrefix=""/>
    <structured:Metadata xmi:id="17"
                        patientIdentifier="1"
                        patientID="0"
                        sourceData="23"/>
    <structured:DocumentPath xmi:id="35"
                            documentPath="D:__FilesInput11.txt"/>
    <Matrix:Segment xmi:id="37"
                        sofa="1"
                        begin="0"
                        end="16975"
                        id="SIMPLE_SEGMENT"
                        preferredText="SIMPLE_SEGMENT"/>
    <Matrix:Customer xmi:id="44"
                        sofa="1"
                        begin="0"
                        end="15"
                        Matrix:CustomerNumber="0"/>
    <Matrix:Customer xmi:id="50"
                        sofa="1"
                        begin="17"
                        end="33"
                        Matrix:CustomerNumber="1"/>
    <Matrix:Customer xmi:id="56"
                        sofa="1"
                        begin="47"
                        end="62"
                        Matrix:CustomerNumber="2"/>
    <Matrix:Customer xmi:id="62"
                        sofa="1"
                        begin="65"
                        end="80"
                        Matrix:CustomerNumber="3"/>

1 ответ

Лучший ответ

Мне пришлось исправить входной XML, добавив поддельное пространство имен. Лучше использовать собственные методы XQuery: .nodes() и .value() и держаться подальше от проприетарного OPENXML() Microsoft и его сопутствующих API.

Проверить это.

XML

<?xml version="1.0" encoding="UTF-8"?>
<xmi:XMI xmlns:xmi="http://www.omg.org/XMI"
         xmlns:util="http:///org/apache/ctakes/typesystem/type/util.ecore"
         xmlns:tcas="http:///uima/tcas.ecore" xmlns:cas="http:///uima/cas.ecore"
         xmlns:type10="http:///org/cleartk/syntax/constituent/type.ecore"
         xmlns:ne="http:///org/cleartk/type/ne.ecore"
         xmlns:textsem="http:///org/apache/ctakes/typesystem/type/textsem.ecore"
         xmlns:types2="http:///org/apache/ctakes/assertion/zoner/types.ecore"
         xmlns:type6="http:///org/apache/ctakes/smokingstatus/i2b2/type.ecore"
         xmlns:refsem="http:///org/apache/ctakes/typesystem/type/refsem.ecore"
         xmlns:type11="http:///org/cleartk/syntax/dependency/type.ecore"
         xmlns:type="http:///de/tudarmstadt/ukp/dkpro/core/api/metadata/type.ecore"
         xmlns:type14="http:///org/cleartk/util/type.ecore"
         xmlns:assertion="http:///org/apache/ctakes/typesystem/type/temporary/assertion.ecore"
         xmlns:type8="http:///org/cleartk/score/type.ecore"
         xmlns:syntax="http:///org/apache/ctakes/typesystem/type/syntax.ecore"
         xmlns:type9="http:///org/cleartk/srl/type.ecore"
         xmlns:type2="http:///org/apache/ctakes/constituency/parser/uima/type.ecore"
         xmlns:types="http:///org/apache/ctakes/assertion/medfacts/types.ecore"
         xmlns:type7="http:///org/apache/ctakes/smokingstatus/type.ecore"
         xmlns:relation="http:///org/apache/ctakes/typesystem/type/relation.ecore"
         xmlns:type12="http:///org/cleartk/timeml/type.ecore"
         xmlns:type5="http:///org/apache/ctakes/sideeffect/type.ecore"
         xmlns:type15="http:///org/cleartk/ne/type.ecore"
         xmlns:type13="http:///org/cleartk/token/type.ecore"
         xmlns:structured="http:///org/apache/ctakes/typesystem/type/structured.ecore"
         xmlns:textspan="http:///org/apache/ctakes/typesystem/type/textspan.ecore"
         xmlns:libsvm="http:///org/apache/ctakes/smokingstatus/type/libsvm.ecore"
         xmlns:type3="http:///org/apache/ctakes/coreference/type.ecore"
         xmlns:type4="http:///org/apache/ctakes/drugner/type.ecore"
         xmlns:Matrix="http://someURL"
         xmi:version="2.0">
    <cas:NULL xmi:id="0"/>
    <tcas:DocumentAnnotation xmi:id="8" sofa="1" begin="0" end="16975"
                             language="x-unspecified"/>
    <structured:DocumentID xmi:id="13" documentID="1"/>
    <structured:DocumentIdPrefix xmi:id="15" documentIdPrefix=""/>
    <structured:Metadata xmi:id="17" patientIdentifier="1" patientID="0"
                         sourceData="23"/>
    <structured:DocumentPath xmi:id="35" documentPath="D:__FilesInput11.txt"/>
    <Matrix:Segment xmi:id="37" sofa="1" begin="0" end="16975"
                    id="SIMPLE_SEGMENT" preferredText="SIMPLE_SEGMENT"/>
    <Matrix:Customer xmi:id="44" sofa="1" begin="0" end="15"
                     Matrix:CustomerNumber="0"/>
    <Matrix:Customer xmi:id="50" sofa="1" begin="17" end="33"
                     Matrix:CustomerNumber="1"/>
    <Matrix:Customer xmi:id="56" sofa="1" begin="47" end="62"
                     Matrix:CustomerNumber="2"/>
    <Matrix:Customer xmi:id="62" sofa="1" begin="65" end="80"
                     Matrix:CustomerNumber="3"/>
</xmi:XMI>

SQL

;WITH XMLNAMESPACES ('http://www.omg.org/XMI' AS xmi
    , 'http://someURL' AS Matrix), rs (xmldata) AS 
(
    SELECT CONVERT (XML, BulkColumn) 
    FROM OPENROWSET (BULK N'e:Temp2027.xml', SINGLE_BLOB) AS XmlData
)
SELECT c.value('@xmi:id', 'INT') AS xml_id
    , c.value('@sofa', 'INT') AS sofa
    , c.value('@begin', 'INT') AS [begin]
    , c.value('@end', 'INT') AS [end]
    , c.value('@Matrix:CustomerNumber', 'INT') AS CustomerNumber
FROM rs
    CROSS APPLY xmldata.nodes('/xmi:XMI/Matrix:Customer') AS t(c);

Вывод

+--------+------+-------+-----+----------------+
| xml_id | sofa | begin | end | CustomerNumber |
+--------+------+-------+-----+----------------+
|     44 |    1 |     0 |  15 |              0 |
|     50 |    1 |    17 |  33 |              1 |
|     56 |    1 |    47 |  62 |              2 |
|     62 |    1 |    65 |  80 |              3 |
+--------+------+-------+-----+----------------+


0

Yitzhak Khabinsky
25 Дек 2020 в 10:27

Это предупреждение, а не ошибка. Таким образом, XML все еще можно использовать, но он сломан. Лучшим решением будет восстановление XML — определение пространства имен.

Определение namesapce не будет работать автоматически. Префикс пространства имен является только псевдонимом, где фактическое пространство имен является значением атрибута xmlns. Псевдоним действителен только для элемента и его потомков. Приложение script/, которое генерирует XML, должно быть восстановлено, чтобы оно добавило определение пространства имен.

<meta xmlns:edf="urn:example">
    <info gamemodes="race" type="map" edf:represent="false"></info>
</meta>

Парсер разрешит пространство имен. Вы можете читать «edf: представлять» как «{urn: example} представляют».

Однако вы можете блокировать ошибки и предупреждения синтаксического анализа, используя libxml_use_internal_errors().

$xml = <<<'XML'
<meta>
    <info gamemodes="race" type="map" edf:represent="false"></info>
</meta>
XML;

libxml_use_internal_errors(TRUE);

$dom = new DOMDocument();
$dom->loadXml($xml);

echo $dom->saveXml();

Вывод:

<?xml version="1.0"?>
<meta>
    <info gamemodes="race" type="map" represent="false"/>
</meta>

С помощью libxml_get_errors() вы можете реализовать свою собственную обработку ошибок.

Как вы можете видеть на выходе, синтаксический анализатор XML удалил префикс пространства имен. Это означает, что «представлять» теперь является атрибутом без пространства имен, оно изменило его идентификатор. Будьте очень осторожны, represent и {urn:example}represent — это два разных имени, вы теряете соответствующую контекстную информацию.

Вопрос:

Пожалуйста помоги. После прочтения всех google и stackoverflow 🙂 мой мозг больше не работает.

У меня ниже TSQL (работает на SQL Server 2012)

Я не могу понять, где мне нужно объявить мое пространство имен:? И сколько пространств имен мне нужно объявить?

DECLARE @XML AS XML
DECLARE @hDoc AS INT

SELECT @XML = '<GetAssetWarrantyResponse xmlns="http://tempuri.org/">
<GetAssetWarrantyResult xmlns:a="http://schemas.datacontract.org/2004/07/Dell.AWR.Domain.Asset" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:Faults />
<a:Response>
<a:DellAsset>
<a:AssetParts i:nil="true" />
<a:CountryLookupCode>5252</a:CountryLookupCode>
<a:CustomerNumber>645651</a:CustomerNumber>
</a:DellAsset>
</a:Response>
</GetAssetWarrantyResult>
</GetAssetWarrantyResponse>'

EXEC sp_xml_preparedocument @hDoc OUTPUT, @XML

SELECT CountryLookupCode
FROM OPENXML(@hDoc, 'GetAssetWarrantyResponse/GetAssetWarrantyResult/a:Response/a:DellAsset')
WITH
(
CountryLookupCode   [nvarchar](20)  'a:CountryLookupCode'
)

EXEC sp_xml_removedocument @hDoc
GO

Лучший ответ:

Вы должны указать префиксы пространства имен при вызове sp_xml_preparedocument. В этом случае у вас есть a пространство имен и пространство имен по умолчанию (один без префикса: xmlns="...."):

EXEC sp_xml_preparedocument 
        @hDoc OUTPUT
        , @XML
        , '<root xmlns:d="http://tempuri.org/" xmlns:a="http://schemas.datacontract.org/2004/07/Dell.AWR.Domain.Asset"/>'

И правильно используйте зарегистрированные префиксы:

SELECT CountryLookupCode
FROM OPENXML(@hDoc, 'd:GetAssetWarrantyResponse/d:GetAssetWarrantyResult/a:Response/a:DellAsset')
WITH 
(
    CountryLookupCode   [nvarchar](20)  'a:CountryLookupCode'
)

Ответ №1

Я бы использовал встроенную встроенную поддержку XQuery в SQL Server:

DECLARE @XML AS XML

SELECT @XML = '<GetAssetWarrantyResponse xmlns="http://tempuri.org/">
<GetAssetWarrantyResult xmlns:a="http://schemas.datacontract.org/2004/07/Dell.AWR.Domain.Asset" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:Faults />
<a:Response>
<a:DellAsset>
<a:AssetParts i:nil="true" />
<a:CountryLookupCode>5252</a:CountryLookupCode>
<a:CustomerNumber>645651</a:CustomerNumber>
</a:DellAsset>
</a:Response>
</GetAssetWarrantyResult>
</GetAssetWarrantyResponse>'

;WITH XMLNAMESPACES(DEFAULT 'http://tempuri.org/', 'http://schemas.datacontract.org/2004/07/Dell.AWR.Domain.Asset' AS ns)
SELECT
@XML.value('(GetAssetWarrantyResponse/GetAssetWarrantyResult/ns:Response/ns:DellAsset/ns:CountryLookupCode)[1]', 'int')

В терминах пространств имен XML: вам необходимо определить все те, которые используются в вашем документе XML, до момента, когда вы хотите получить данные из

Logo
MurCode

  • Форумы
  • Поиск
  • О проекте

genok

Дата: 27.08.2021 22:39:22

не победил я корявый импорт WSDL и решил делать XML вручную с помощью IXMLDocument
затык на следующем: нужно получить строку вот такого вида:

 <caseDto xmlns:d4p1="http://schemas.datacontract.org/2004/07/N3.EMK.Dto.Case" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" i:type="d4p1:CaseAmb"/>

документ формирую так:

  
    XML:=NewXMLDocument;
    XML.Options := XML.Options + [doNodeAutoIndent];
    XML.Encoding:='UTF-8';

    with XML.AddChild('s:Envelope', 'http://schemas.xmlsoap.org/soap/envelope/') do
      With AddChild('Body').AddChild('AddCase', 'http://tempuri.org/') do
          caseDto:=AddChild('caseDto');

    caseDto.DeclareNamespace('d4p1', 'http://schemas.datacontract.org/2004/07/N3.EMK.Dto.Case');
    caseDto.DeclareNamespace('i', 'http://www.w3.org/2001/XMLSchema-instance');
//    caseDto.SetAttributeNS('xmlns:d4p1', '', 'http://schemas.datacontract.org/2004/07/N3.EMK.Dto.Case');
//    caseDto.SetAttributeNS('xmlns:i', '', 'http://www.w3.org/2001/XMLSchema-instance');
//    caseDto.SetAttributeNS('i:type', '', 'd4p1:CaseAmb');
    caseDto.SetAttributeNS('type', '', 'd4p1:CaseAmb');

получается почти как нужно:

 <caseDto xmlns:d4p1="http://schemas.datacontract.org/2004/07/N3.EMK.Dto.Case" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" type="d4p1:CaseAmb"/>

но если сделать caseDto.SetAttributeNS(‘

i:type‘, », ‘d4p1:CaseAmb’)
то в момент формирования документа получаю ошибку ссылка на необъявленный префикс пространства имен i
где накосячил, чего не вижу?

_Vasilisk_

Дата: 28.08.2021 00:37:58

Вы наугад программируете? Не пробовали читать документацию?

caseDto.SetAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'i:type', 'd4p1:CaseAmb');

genok

Дата: 28.08.2021 03:40:55

_Vasilisk_
Вы наугад программируете? Не пробовали читать документацию?

caseDto.SetAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'i:type', 'd4p1:CaseAmb');

спасибо, вот так получилось:

caseDto.SetAttributeNS('i:type', 'http://www.w3.org/2001/XMLSchema-instance', 'd4p1:CaseAmb');

обычно смотрю описания методов прям в исходниках, но вот что-то такой подход засбоил
сразу спрошу еще: как сделать чтобы дочерние строки автоматически префиксы добавляли
делаю так:

caseDto.ChildValues['Comment']:='тестовая запись случая';

на выходе

<IdCaseMis>223</IdCaseMis>

а надо

<d4p1:IdCaseMis>223</d4p1:IdCaseMis>

или руками в каждый пункт добавлять?

_Vasilisk_

Дата: 28.08.2021 12:14:30

genok
или руками в каждый пункт добавлять?

Нужно при вызове CreateNode/AddChild указывать нужный неймспейс.

genok

Дата: 28.08.2021 13:25:26

_Vasilisk_
genok
или руками в каждый пункт добавлять?

Нужно при вызове CreateNode/AddChild указывать нужный неймспейс.

но если я так делаю, то строка выходная меняет свой вид и не опознается сервисом

сейчас с вашей помощью код выглядит так:

    caseDto:=AddChild('caseDto');
    caseDto.DeclareNamespace('d4p1', 'http://schemas.datacontract.org/2004/07/N3.EMK.Dto.Case');
    caseDto.SetAttributeNS('i:type', 'http://www.w3.org/2001/XMLSchema-instance', 'd4p1:CaseAmb');
    caseDto.ChildValues['d4p1:HistoryNumber']:='111'; 

на выходе именно то, что нужно, сервис это слава Богу принимает и ошибок нет

      
     <caseDto xmlns:d4p1="http://schemas.datacontract.org/2004/07/N3.EMK.Dto.Case" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" i:type="d4p1:CaseAmb">
        <d4p1:HistoryNumber>111</d4p1:HistoryNumber>

в принципе, руками несложно префикс добавить, ибо любые испробованные мной варианты добавления НС при создании ноды меняют её описание и сервис такое не опознает уже.
Огромное спасибо вам за помощь!!

Маркет42 - место для твоих разработок

 

RarusTechDay - открытая техническая конференция программистов 1С.

 


1С:Предприятие

:: 1С:Предприятие 8 общая

Я
   Sova789

06.03.17 — 12:35

При выгрузке из ЗУП  (релиз 2.5.114.1)  файла СЗВ-М  в программу для проверки CheckPFR  появляется ошибка: ссылка на необъявленный префикс пространства имен «DEF». Может кто подскажет, в чем дело?

   piter3

1 — 06.03.17 — 12:36

может и так

http://www.buhsoft.ru/forums/showthread.php?t=36372&page=2

  

Sova789

2 — 06.03.17 — 12:40

(1) Понятно!  Спасибо!


Список тем форума

Наведи порядок в своей работе используя конфигурацию 1C «Управление IT-отделом 8»

Ветка сдана в архив.

  • Ошибка разбора пакета meizu m5s
  • Ошибка разбора xml сообщения
  • Ошибка разбора пакета meizu m5c
  • Ошибка разбора xml синтаксическая
  • Ошибка разбора xml при обновлении