LINQ to XML НАВИГАЦИОННЫЙ ФАЙЛ

1

Я новичок в LinQ для XML, и у меня возникли проблемы с использованием Xdocument (в данном случае) для извлечения определенных значений из файла XML и для начала, по крайней мере, вернуть его на консоль.

В XLM мне нужно отображать только определенные значения; 4GB493594008000-JENEXP18082014A, A1, 20 (в элементе staticValue) и т.д.

Любые указатели будут очень благодарны - спасибо.

В рассматриваемом XML

  <?xml version="1.0" encoding="utf-8"?>
<declarationGbResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="demo.com/test/DeclarationGbResponse">
  <declarationIdentity>
    <declarationUcr xmlns="demo.org.uk/DeclarationGbIdentityType">4GB493594008000-JENEXP18082014A</declarationUcr>
  </declarationIdentity>
  <responseType>ACC</responseType>
  <responseTime>2014-08-18T13:36:32.79</responseTime>
  <isFirstAcceptanceResponse>true</isFirstAcceptanceResponse>
  <externalReferences/>
  <!-- element -->
  <acceptanceResponse>
  <!-- element -->
    <ICS xmlns="demo.org.uk/test/DeclarationGbAcceptanceResponse">A1</ICS>
    <entryRoute xmlns="demo.org.uk/test/DeclarationGbAcceptanceResponse">H</entryRoute>
    <statusOfExportEntry xmlns="demo.org.uk/test/DeclarationGbAcceptanceResponse">1</statusOfExportEntry>
    <entryTime xmlns="demo.org.uk/test/DeclarationGbAcceptanceResponse">2014-08-18T13:36:00</entryTime>
    <entryEpuNumber xmlns="demo.org.uk/test/DeclarationGbAcceptanceResponse">120</entryEpuNumber>
    <entryNumber xmlns="demo.org.uk/test/DeclarationGbAcceptanceResponse">A05605F</entryNumber>
    <entryVersionNumber xmlns="demo.org.uk/test/DeclarationGbAcceptanceResponse">1</entryVersionNumber>
    <movementReferenceNumber xmlns="demo.org.uk/test/DeclarationGbAcceptanceResponse">14GB08X33073603018</movementReferenceNumber>
    <declarationExchangeRate xmlns="demo.org.uk/test/DeclarationGbAcceptanceResponse">1</declarationExchangeRate>
    <declarationCurrency xmlns="demo.org.uk/test/DeclarationGbAcceptanceResponse">
      <currencyCode xmlns="demo.org.uk/test/Currency">GBP</currencyCode>
    </declarationCurrency>
    <customsValueForDuty xmlns="demo.org.uk/test/DeclarationGbAcceptanceResponse">
      <value xmlns="demo.org.uk/test/MonetaryType">20</value>
    </customsValueForDuty>
    <customsDutyPayable xmlns="demo.org.uk/test/DeclarationGbAcceptanceResponse">
      <value xmlns="demo.org.uk/test/MonetaryType">0</value>
    </customsDutyPayable>
    <deferedRevenue xmlns="demo.org.uk/test/DeclarationGbAcceptanceResponse">
      <value xmlns="demo.org.uk/test/MonetaryType">0</value>
    </deferedRevenue>
    <immediateRevenue xmlns="demo.org.uk/test/DeclarationGbAcceptanceResponse">
      <value xmlns="demo.org.uk/test/MonetaryType">0</value>
    </immediateRevenue>
    <revenuePayable xmlns="demo.org.uk/test/DeclarationGbAcceptanceResponse">
      <value xmlns="demo.org.uk/test/MonetaryType">0</value>
    </revenuePayable>
    <itemResponses xmlns="demo.org.uk/test/DeclarationGbAcceptanceResponse">
      <itemResponse>
        <itemNumber xmlns="demo.org.uk/test/DeclarationGbItemResponse">1</itemNumber>
        <statisticalValue xmlns="demo.org.uk/test/DeclarationGbItemResponse">
          <value xmlns="demo.org.uk/test/MonetaryType">20</value>
        </statisticalValue>
      </itemResponse>
    </itemResponses>
  </acceptanceResponse>
</declarationGbResponse
Теги:
linq-to-xml

1 ответ

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

В вашем XML есть разные пространства имен по умолчанию, объявленные на разных уровнях, вам нужно быть очень осторожными, чтобы видеть, какой элемент находится в пространстве имен.

В случае, если вы не знаете, пространство имен по умолчанию выводится для элементов-потомков. Средство, элемент, в котором объявлено пространство имен по умолчанию, и все его потомки без префикса и без другого объявления пространства имен по умолчанию рассматриваются в том же пространстве имен, пространстве имен предков. Например, из-за отсутствия префикса или другого объявления пространства имен по умолчанию, <acceptanceResponse> рассматривается в пространстве имен этого родителя, который является "demo.com/test/DeclarationGbResponse".

Чтобы выбрать элемент в пространстве имен, вы можете использовать " XNamespace +element локальное имя":

XDocument doc = /* load your XML to XDocument */
XNamespace gbResponse = "demo.com/test/DeclarationGbResponse";
XNamespace gbIdentityType = "demo.org.uk/DeclarationGbIdentityType";
XNamespace gbAcceptanceRespons = "demo.org.uk/test/DeclarationGbAcceptanceResponse";
XNamespace gbItemResponse = "demo.org.uk/test/DeclarationGbItemResponse";
XNamespace monetaryType = "demo.org.uk/test/MonetaryType";
var declarationUcr = (string)doc.Root
                                .Element(gbResponse + "declarationIdentity")
                                .Element(gbIdentityType + "declarationUcr");
var ICS = (string)doc.Root
                     .Element(gbResponse + "acceptanceResponse")
                     .Element(gbAcceptanceRespons + "ICS");
var value = (string)doc.Root
                       .Element(gbResponse + "acceptanceResponse")
                       .Element(gbAcceptanceRespons + "itemResponses")
                       .Element(gbAcceptanceRespons + "itemResponse")
                       .Element(gbItemResponse + "statisticalValue")
                       .Element(monetaryType + "value");
Console.WriteLine(declarationUcr);
Console.WriteLine(ICS);
Console.WriteLine(value);

Ещё вопросы

Сообщество Overcoder
Наверх
Меню