Не удается получить путь к элементу XML в SOAP

У меня есть XML-файл для чтения на VB.NET. Мой код относится к файлу.

Как я могу прочитать значение <Value>, связанного с <Key> LNGYIL?

Не удается получить путь к элементу XML в SOAP

Мой код:

Dim doc As XDocument
        doc = XDocument.Load("c:\jpan\faturalar.xml")
        Dim lngyil= (
       From v In doc.<soap>.<soap>.<IntegrationGetEntitySetWithPacketLoginResponse>.<IntegrationGetEntitySetWithPacketLoginResult>.<ResultEntitySet>.<CustomData>.<ArrayOfClsDictionaryOfStringObject>.<clsDictionaryOfStringObject>
       Where v.<Key>.Value = "LNGYIL"
       Select v.<Value>.Value
            ).Single()
        ListBox1.Items.Insert(0, lngyil)

Источник XML:

<soap:Envelope xmlns:soap = "http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd = "http://www.w3.org/2001/XMLSchema"><soap:Body><IntegrationGetEntitySetWithPacketLoginResponse xmlns = "http://integration.univera.com.tr"><IntegrationGetEntitySetWithPacketLoginResult><ResultString>OK</ResultString><IsSuccess>true</IsSuccess><ResultEntitySet><GorevSonucBilgiler/><DistUnvan/><PaketAdi/><Warnings/><PaketTanimlar><clsPaketTanim><Kod xsi:nil = "true"/><Tabloadi>CUSTOMVIEW_ENTVIEWFATURAGENERIC_OZGUN</Tabloadi><Viewadi>CUSTOMVIEW_ENTVIEWFATURAGENERIC_OZGUN</Viewadi><Yon xsi:nil = "true"/><Kriter>"(LNGDISTKOD = 12) AND BYTTUR IN(0,1) AND (LNGYIL = 2018) AND (BYTDURUM = 0)"</Kriter><Durum xsi:nil = "true"/></clsPaketTanim></PaketTanimlar><SatirBazliTransaction>false</SatirBazliTransaction><LogKategori>0</LogKategori><IntegrationGorevSonucTip>0</IntegrationGorevSonucTip><errorLoglist/><SCCall>false</SCCall><ReturnLoglist>false</ReturnLoglist><StokSil>false</StokSil><CustomData><ArrayOfClsDictionaryOfStringObject><clsDictionaryOfStringObject><Key>LNGYIL</Key><Value xsi:type = "xsd:int">2018</Value></clsDictionaryOfStringObject><clsDictionaryOfStringObject><Key>LNGDISTKOD</Key><Value xsi:type = "xsd:int">12</Value></clsDictionaryOfStringObject><clsDictionaryOfStringObject><Key>TXTDISTKOD</Key><Value xsi:type = "xsd:string">SH012</Value></clsDictionaryOfStringObject><clsDictionaryOfStringObject><Key>TXTSTKOD</Key><Value xsi:type = "xsd:string">SH010</Value></clsDictionaryOfStringObject></ArrayOfClsDictionaryOfStringObject></CustomData></ResultEntitySet></IntegrationGetEntitySetWithPacketLoginResult></IntegrationGetEntitySetWithPacketLoginResponse></soap:Body></soap:Envelope>

В настоящее время ничего не получаю.

stackoverflow.com/questions/15933333/how-to-read-an-xml-file Найдите решение здесь
Prakash 26.11.2018 08:29

Спасибо, но в теге узла нет стандартных данных.

Hasan Fehmi B. 26.11.2018 08:46
Стоит ли изучать PHP в 2026-2027 годах?
Стоит ли изучать PHP в 2026-2027 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Приемы CSS-макетирования - floats и Flexbox
Приемы CSS-макетирования - floats и Flexbox
Здравствуйте, друзья-студенты! Готовы совершенствовать свои навыки веб-дизайна? Сегодня в нашем путешествии мы рассмотрим приемы CSS-верстки - в...
Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
0
2
169
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Вам нужно закодировать его, чтобы иметь дело с пространствами имен. Один из способов - использовать такие операторы Imports:

Imports <xmlns:soap = "http://schemas.xmlsoap.org/soap/envelope/">
Imports <xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance">
Imports <xmlns:xsd = "http://www.w3.org/2001/XMLSchema">
Imports <xmlns = "http://integration.univera.com.tr">

Module Module1

    Sub Main()
        Dim x As XElement = <soap:Envelope xmlns:soap = "http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd = "http://www.w3.org/2001/XMLSchema">
                                <soap:Body>
                                    <IntegrationGetEntitySetWithPacketLoginResponse xmlns = "http://integration.univera.com.tr">
                                        <IntegrationGetEntitySetWithPacketLoginResult>
                                            <ResultString>OK</ResultString>
                                            <IsSuccess>true</IsSuccess>
                                            <ResultEntitySet>
                                                <GorevSonucBilgiler/>
                                                <DistUnvan/>
                                                <PaketAdi/>
                                                <Warnings/>
                                                <PaketTanimlar>
                                                    <clsPaketTanim>
                                                        <Kod xsi:nil = "true"/>
                                                        <Tabloadi>CUSTOMVIEW_ENTVIEWFATURAGENERIC_OZGUN</Tabloadi>
                                                        <Viewadi>CUSTOMVIEW_ENTVIEWFATURAGENERIC_OZGUN</Viewadi>
                                                        <Yon xsi:nil = "true"/>
                                                        <Kriter>"(LNGDISTKOD = 12) AND BYTTUR IN(0,1) AND (LNGYIL = 2018) AND (BYTDURUM = 0)"</Kriter>
                                                        <Durum xsi:nil = "true"/>
                                                    </clsPaketTanim>
                                                </PaketTanimlar>
                                                <SatirBazliTransaction>false</SatirBazliTransaction>
                                                <LogKategori>0</LogKategori>
                                                <IntegrationGorevSonucTip>0</IntegrationGorevSonucTip>
                                                <errorLoglist/>
                                                <SCCall>false</SCCall>
                                                <ReturnLoglist>false</ReturnLoglist>
                                                <StokSil>false</StokSil>
                                                <CustomData>
                                                    <ArrayOfClsDictionaryOfStringObject>
                                                        <clsDictionaryOfStringObject>
                                                            <Key>LNGYIL</Key>
                                                            <Value xsi:type = "xsd:int">2018</Value>
                                                        </clsDictionaryOfStringObject>
                                                        <clsDictionaryOfStringObject>
                                                            <Key>LNGDISTKOD</Key>
                                                            <Value xsi:type = "xsd:int">12</Value>
                                                        </clsDictionaryOfStringObject>
                                                        <clsDictionaryOfStringObject>
                                                            <Key>TXTDISTKOD</Key>
                                                            <Value xsi:type = "xsd:string">SH012</Value>
                                                        </clsDictionaryOfStringObject>
                                                        <clsDictionaryOfStringObject>
                                                            <Key>TXTSTKOD</Key>
                                                            <Value xsi:type = "xsd:string">SH010</Value>
                                                        </clsDictionaryOfStringObject>
                                                    </ArrayOfClsDictionaryOfStringObject>
                                                </CustomData>
                                            </ResultEntitySet>
                                        </IntegrationGetEntitySetWithPacketLoginResult>
                                    </IntegrationGetEntitySetWithPacketLoginResponse>
                                </soap:Body>
                            </soap:Envelope>

        Dim doc = New XDocument(x)

        Dim q = doc.<soap:Envelope>.<soap:Body>.<IntegrationGetEntitySetWithPacketLoginResponse>.<IntegrationGetEntitySetWithPacketLoginResult>.<ResultEntitySet>.<CustomData>.<ArrayOfClsDictionaryOfStringObject>.<clsDictionaryOfStringObject>

        Dim lngyil = (
                       From v In q
                       Where v.<Key>.Value = "LNGYIL"
                       Select v.<Value>.Value
                     ).Single()

        Console.WriteLine(lngyil)

        Console.ReadLine()

    End Sub

End Module

Выходы:

2018

P.S. У меня есть подозрение, что xmlns = "http://integration.univera.com.tr" недействителен, и это должно быть что-то вроде xmlns:univera = "http://integration.univera.com.tr". Это изменение делает возможным следующее ...

Второй вариант

Вместо использования операторов Imports вы можете использовать XmlNamespaceManager следующим образом:

Imports System.Xml
Imports System.Xml.XPath

Module Module1

    Sub Main()
        Dim x As XElement = <soap:Envelope xmlns:soap = "http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd = "http://www.w3.org/2001/XMLSchema">
                                <soap:Body>
                                    <IntegrationGetEntitySetWithPacketLoginResponse xmlns:univera = "http://integration.univera.com.tr">
                                        <IntegrationGetEntitySetWithPacketLoginResult>
                                            <ResultString>OK</ResultString>
                                            <IsSuccess>true</IsSuccess>
                                            <ResultEntitySet>
                                                <GorevSonucBilgiler/>
                                                <DistUnvan/>
                                                <PaketAdi/>
                                                <Warnings/>
                                                <PaketTanimlar>
                                                    <clsPaketTanim>
                                                        <Kod xsi:nil = "true"/>
                                                        <Tabloadi>CUSTOMVIEW_ENTVIEWFATURAGENERIC_OZGUN</Tabloadi>
                                                        <Viewadi>CUSTOMVIEW_ENTVIEWFATURAGENERIC_OZGUN</Viewadi>
                                                        <Yon xsi:nil = "true"/>
                                                        <Kriter>"(LNGDISTKOD = 12) AND BYTTUR IN(0,1) AND (LNGYIL = 2018) AND (BYTDURUM = 0)"</Kriter>
                                                        <Durum xsi:nil = "true"/>
                                                    </clsPaketTanim>
                                                </PaketTanimlar>
                                                <SatirBazliTransaction>false</SatirBazliTransaction>
                                                <LogKategori>0</LogKategori>
                                                <IntegrationGorevSonucTip>0</IntegrationGorevSonucTip>
                                                <errorLoglist/>
                                                <SCCall>false</SCCall>
                                                <ReturnLoglist>false</ReturnLoglist>
                                                <StokSil>false</StokSil>
                                                <CustomData>
                                                    <ArrayOfClsDictionaryOfStringObject>
                                                        <clsDictionaryOfStringObject>
                                                            <Key>LNGYIL</Key>
                                                            <Value xsi:type = "xsd:int">2018</Value>
                                                        </clsDictionaryOfStringObject>
                                                        <clsDictionaryOfStringObject>
                                                            <Key>LNGDISTKOD</Key>
                                                            <Value xsi:type = "xsd:int">12</Value>
                                                        </clsDictionaryOfStringObject>
                                                        <clsDictionaryOfStringObject>
                                                            <Key>TXTDISTKOD</Key>
                                                            <Value xsi:type = "xsd:string">SH012</Value>
                                                        </clsDictionaryOfStringObject>
                                                        <clsDictionaryOfStringObject>
                                                            <Key>TXTSTKOD</Key>
                                                            <Value xsi:type = "xsd:string">SH010</Value>
                                                        </clsDictionaryOfStringObject>
                                                    </ArrayOfClsDictionaryOfStringObject>
                                                </CustomData>
                                            </ResultEntitySet>
                                        </IntegrationGetEntitySetWithPacketLoginResult>
                                    </IntegrationGetEntitySetWithPacketLoginResponse>
                                </soap:Body>
                            </soap:Envelope>

        Dim doc = New XDocument(x)

        Dim nt As NameTable = New NameTable()
        Dim nsmgr As XmlNamespaceManager = New XmlNamespaceManager(nt)
        nsmgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/")
        nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance")
        nsmgr.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema")
        nsmgr.AddNamespace("univera", "http://integration.univera.com.tr")

        Dim a = doc.XPathSelectElements("/soap:Envelope/soap:Body/IntegrationGetEntitySetWithPacketLoginResponse/IntegrationGetEntitySetWithPacketLoginResult/ResultEntitySet/CustomData/ArrayOfClsDictionaryOfStringObject/clsDictionaryOfStringObject", nsmgr)
        Dim lngyil2 = (
                       From v In a
                       Where v.XPathSelectElement("Key").Value = "LNGYIL"
                       Select v.XPathSelectElement("Value").Value
                     ).Single()

        Console.WriteLine(lngyil2)

        Console.ReadLine()

    End Sub

End Module

Дополнительная работа над запросом XPath позволит вам получить значение напрямую, без цикла после него.


Ссылки:

Другие вопросы по теме