Меню

Ошибка разбора 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.

Вопрос:

Пожалуйста помоги. После прочтения всех 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 — это два разных имени, вы теряете соответствующую контекстную информацию.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка разбора xml сообщения
  • Ошибка разбора xml синтаксическая