Узел XML из списка узлов не читает значения текущего цикла_ Решено - PullRequest
0 голосов
/ 09 октября 2019

Я пытаюсь пройтись по XML-файлу и отобразить значение для типа в сообщении. Но мой код неоднократно дает ему значения первой записи.

Ниже приведен мой XML

<Request deploymentMode="test">
  <ConfirmationRequest>
    <ConfirmationHeader noticeDate="2019-10-03T01:53:54+0200" type="accept" operation="new" confirmID="0002933085">...</ConfirmationHeader>
    <OrderReference orderID="50084">...</OrderReference>
    <ConfirmationItem lineNumber="000010" quantity="16.000">
      <UnitOfMeasure>CT</UnitOfMeasure>
      <ConfirmationStatus type="rejected" quantity="16.000">
        <UnitOfMeasure>CT</UnitOfMeasure>
        <Comments>ConfirmedQuantity:0.000</Comments>
        <Comments>reject reason: EDI 855 Rejected: Out of Stock</Comments>
      </ConfirmationStatus>
    </ConfirmationItem>
    <ConfirmationItem lineNumber="000020" quantity="144.000">
      <UnitOfMeasure>CT</UnitOfMeasure>
      <ConfirmationStatus deliveryDate="2019-10-02T07:00:00+0200" type="accepted" quantity="144.000">
        <UnitOfMeasure>CT</UnitOfMeasure>
        <Comments>ConfirmedQuantity:144.000</Comments>
      </ConfirmationStatus>
    </ConfirmationItem>
    <ConfirmationItem lineNumber="000030" quantity="45.000">
      <UnitOfMeasure>CT</UnitOfMeasure>
      <ConfirmationStatus deliveryDate="2019-10-02T07:00:00+0200" type="partial-accept" quantity="45.000">
        <UnitOfMeasure>CT</UnitOfMeasure>
        <Comments>ConfirmedQuantity:45.000</Comments>
        <Comments>Partial Accept reason -Out of Stock etc.</Comments>
      </ConfirmationStatus>
    </ConfirmationItem>
    <ConfirmationItem lineNumber="000040" quantity="65.000">
      <UnitOfMeasure>CT</UnitOfMeasure>
      <ConfirmationStatus deliveryDate="2019-10-02T07:00:00+0200" type="accepted" quantity="65.000">
        <UnitOfMeasure>CT</UnitOfMeasure>
        <Comments>ConfirmedQuantity:65.000</Comments>
      </ConfirmationStatus>
    </ConfirmationItem>
  </ConfirmationRequest>
</Request>

Мой код выглядит следующим образом.

XmlNodeList xnList = xmlDoc.SelectNodes("//ConfirmationRequest/ConfirmationItem");

                    foreach (XmlNode xn in xnList)
                    {
                     OrderNumber = null;
                        LineNumber = 0;
                        Quantity = 0;
                        UnitOfMeasure = null;
                        DeliveryDate = null;
                        Type = null;
                        ConfirmationStatus_Quantity = 0;
                        ConfirmationStatus_Unitofmeasure = null;
                        LineitemComments_1 = null;
                        LineitemComments_2 = null;
                        LineitemComments_3 = null;
                        LineitemComments_4 = null;
                        LineitemComments_5 = null;
                        CreatedDate = null;

                        XmlNode orh = xmlDoc.SelectSingleNode("//Request/ConfirmationRequest/OrderReference");
                        OrderNumber = (orh.Attributes["orderID"].Value == null) ? null : orh.Attributes["orderID"].Value;
                        LineNumber = int.Parse(xn.Attributes[0].Value == null ? null : xn.Attributes[0].Value);
                        Quantity = Convert.ToDecimal(xn.Attributes[1].Value == null ? null : xn.Attributes[1].Value);
                        UnitOfMeasure = xn.SelectSingleNode("UnitOfMeasure").InnerText == null ? null : xn.SelectSingleNode("UnitOfMeasure").InnerText;
                        DeliveryDate = xn.SelectSingleNode("//Request/ConfirmationRequest/ConfirmationItem/ConfirmationStatus/@deliveryDate").InnerText == null ? null : xn.SelectSingleNode("//Request/ConfirmationRequest/ConfirmationItem/ConfirmationStatus/@deliveryDate").InnerText;
                        DeliveryDate = DeliveryDate.Substring(0, 10);
                        Type = xn.SelectSingleNode("//Request/ConfirmationRequest/ConfirmationItem/ConfirmationStatus/@type").InnerText == null ? null : xn.SelectSingleNode("//Request/ConfirmationRequest/ConfirmationItem/ConfirmationStatus/@type").InnerText;

                    }

На каждой итерациия получаю почти все значения, кроме строки атрибута тега

  1. ConfirmationStatus DeliveryDate.
  2. строка атрибута тега ConfirmationStatus Тип.

Дата доставки и Тип не меняются при каждой итерации.

Каждый цикл, который я получаю ниже результатов.

Loop -1: DeliveryDate: 2019-10-02T07: 00: 00 + 0200, тип = отклонено.
Loop -2: DeliveryDate: 2019-10-02T07: 00: 00 + 0200,Тип = отклонено.
Цикл -3: Дата доставки: 2019-10-02T07: 00: 00 + 0200, Тип = отклонено.
Цикл -4: Дата доставки: 2019-10-02T07: 00: 00 + 0200, Тип = отклонено.

Там, где вы можете видеть, что эти значения типа различны для каждого цикла, и нет даты доставки для цикла 1.

Я посмотрел вокруг связанные решения, не смог найти ни одного.

ОТВЕТ

Выяснил, где именно я совершаю ошибку.

Я должен использовать

**xn.SelectSingleNode("ConfirmationStatus/@deliveryDate").InnerText**
**xn.SelectSingleNode("ConfirmationStatus/@type").InnerText**

Вместо

xn.SelectSingleNode("//Request/ConfirmationRequest/ConfirmationItem/ConfirmationStatus/@deliveryDate").InnerText
xn.SelectSingleNode("//Request/ConfirmationRequest/ConfirmationItem/ConfirmationStatus/@type").InnerText

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

Не уверен, что я где-то ошибаюсь.

Просьба предложить.

Спасибо.

1 Ответ

0 голосов
/ 09 октября 2019

Использовать сериализацию XML:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {

            XmlReader reader = XmlReader.Create(FILENAME);

            XmlSerializer serializer = new XmlSerializer(typeof(Request));
            Request request = (Request)serializer.Deserialize(reader);
        }
    }
    public class Request
    {
        [XmlAttribute]
        public string deploymentMode { get; set; }

        public ConfirmationRequest ConfirmationRequest { get; set; } 
    }
    public class ConfirmationRequest
    {
        public ConfirmationHeader ConfirmationHeader { get; set; }
        public OrderReference OrderReference { get; set; }
        [XmlElement]
        public List<ConfirmationItem> ConfirmationItem { get; set; }
    }
    public class ConfirmationHeader
    {
        private DateTime _noticeDate { get; set; }

        [XmlAttribute]
        public string noticeDate {
            get { return _noticeDate.ToString(); }
            set { _noticeDate = DateTime.Parse(value); } 
        }
        [XmlAttribute]
        public string type { get; set; }
        [XmlAttribute]
        public string opertion { get; set; }
        [XmlAttribute]
        public string confirmID { get; set; }


    }
    public class OrderReference
    {
        [XmlAttribute]
        public string orderID { get; set; }

        public string value { get; set; }
    }
    public class ConfirmationItem
    {
        [XmlAttribute]
        public string lineNumber { get; set; }
        [XmlAttribute]
        public decimal quantity { get; set; }
        public string UnitOfMeasure { get; set; }
        public ConfirmationStatus ConfirmationStatus { get; set; } 
    }
    public class ConfirmationStatus
    {
        [XmlAttribute]
        public string type { get; set; }
        [XmlAttribute]
        public decimal quantity { get; set; }
        public string UnitOfMeasure { get; set; }

        [XmlElement]
        public string[] Comments { get; set; }

    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...