2016-05-17 2 views
1

Я пытаюсь прочитать в позиционных значениях адрес конкретного продукта (например, платежные ведомости) в приведенном ниже XMLОбход XML документ с помощью LINQ

   <INI> 
       <ReportTemplate>report_template_land.pdf</ReportTemplate> 
       <ReportAccountID>Reports</ReportAccountID> 
       <!--Table for sending the documents to different channels--> 
       <ChannelDeliveryTable>ChannelDeliveryTable.csv</ChannelDeliveryTable> 
       <Documents> 
       <Payslip> 
         <Address> 
          <distanceInPixelsFromLeft>76</distanceInPixelsFromLeft> 
          <distanceInPixelsFromBottom>580</distanceInPixelsFromBottom> 
          <width>255</width> 
          <height>125</height> 
         </Address> 
      </Payslip> 
        <Invoice> 
        <Address> 
         <distanceInPixelsFromLeft>65</distanceInPixelsFromLeft> 
         <distanceInPixelsFromBottom>580</distanceInPixelsFromBottom> 
         <width>255</width> 
        <height>125</height> 
       </Address> 
       </Invoice> 
       </Documents> 
       </INI> 

я имел несколько попыток, которые все не удались. В приведенном ниже коде показана моя последняя попытка. Не могли бы вы помочь. Заранее спасибо.

  float distanceInPixelsFromLeftAddr; 
      float distanceInPixelsFromBottomAddr; 
      float widthAddr; 
      float heightAddr; 
      try 
      { 
       //var addrPos = from xml in XmlDoc.Elements("Payslip").Descendants("Address") 
       var addrPos = from xml in XmlDoc.Descendants("Payslip").Descendants("Address") 
           select new 

           { 

            distanceInPixelsFromLeftAddr = xml.Element("distanceInPixelsFromLeft").Value, 
            distanceInPixelsFromBottomAddr = xml.Element("distanceInPixelsFromBottom").Value, 
            widthAddr = xml.Element("width").Value, 
            heightAddr = xml.Element("height").Value 

           }; 

       foreach (var node in addrPos) 
       { 

        distanceInPixelsFromLeftAddr = float.Parse(node.distanceInPixelsFromLeftAddr); 
         distanceInPixelsFromBottomAddr = float.Parse(node.distanceInPixelsFromBottomAddr); 
         widthAddr = float.Parse(node.widthAddr); 
         heightAddr = float.Parse(node.heightAddr); 



       } 
      } 
+0

Как не делает это не в состоянии: ошибка или нет результата ('addrPos' содержит 0 товар) или значения ('DistanceInPixelsFromLeftAddr',' widthAddr' и т. д.) являются пустыми или что? – har07

+0

Имеет ли фактический XML пространство имен по умолчанию (что-то в форме 'xmlns =" ​​... "')? – har07

+0

Да У меня есть следующее: user3647451

ответ

0

Учитывая пространства имен по умолчанию не участвуют, следующий запрос отлично работает против XML, публикуемой в вопросе:

var addrPos = from xml in XmlDoc.Descendants("Payslip").Elements("Address") 
      select new 
      { 

       distanceInPixelsFromLeftAddr = (string)xml.Element("distanceInPixelsFromLeft"), 
       distanceInPixelsFromBottomAddr = (string)xml.Element("distanceInPixelsFromBottom"), 
       widthAddr = (float)xml.Element("width"), 
       heightAddr = (float)xml.Element("height") 

      }; 

Обратите внимание, как вы можете бросить XElement непосредственно к соответствующему типу, такие как string или float ,


Смотреть демо ниже или увидеть его вживую в dotnetfiddle:

var raw = @"<INI> 
    <ReportTemplate>report_template_land.pdf</ReportTemplate> 
    <ReportAccountID>Reports</ReportAccountID> 
    <!--Table for sending the documents to different channels--> 
    <ChannelDeliveryTable>ChannelDeliveryTable.csv</ChannelDeliveryTable> 
    <Documents> 
    <Payslip> 
     <Address> 
     <distanceInPixelsFromLeft>76</distanceInPixelsFromLeft> 
     <distanceInPixelsFromBottom>580</distanceInPixelsFromBottom> 
     <width>255</width> 
     <height>125</height> 
     </Address> 
    </Payslip> 
    <Invoice> 
     <Address> 
     <distanceInPixelsFromLeft>65</distanceInPixelsFromLeft> 
     <distanceInPixelsFromBottom>580</distanceInPixelsFromBottom> 
     <width>255</width> 
     <height>125</height> 
     </Address> 
    </Invoice> 
    </Documents> 
</INI> 
"; 
var XmlDoc = XDocument.Parse(raw); 

var addrPos = from xml in XmlDoc.Descendants("Payslip").Elements("Address") 
    select new 
{ 
    distanceInPixelsFromLeftAddr = (string)xml.Element("distanceInPixelsFromLeft"), 
    distanceInPixelsFromBottomAddr = (string)xml.Element("distanceInPixelsFromBottom"), 
    widthAddr = (float)xml.Element("width"), 
    heightAddr = (float)xml.Element("height") 

}; 

foreach (var node in addrPos) 
{ 

    Console.WriteLine(node); 
} 

Выход:

{ distanceInPixelsFromLeftAddr = 76, distanceInPixelsFromBottomAddr = 580, widthAddr = 255, heightAddr = 125 } 
+0

Я не делаю неправильно, но ваш код работает. Благодарю. – user3647451

Смежные вопросы