2012-12-17 75 views
3

幫助獲取各種級別xml中的值。從xml中獲取值(4個級別)

這是XML:

<widgets> 
    <id>95</id> 

    <widget type="1" name="accventas" caption="Ofertas ventas" flags="4"> 
     <service name="pm_venofer_total00001" caption="Pendientes de aceptar" desc="" type="3" detail="1"> 
      <xvalue>20</xvalue> 
      <xcolor>1</xcolor> 
     </service> 
    </widget> 

    <widget type="3" name="today_state" caption="Estado de ventas" flags="4"> 
     <service name="pd_today_orders00001" caption="Pedidos" desc="Nº pedidos del día" type="3" detail="1"> 
      <xvalue>0</xvalue> 
      <xcolor>2</xcolor> 
      <xalert>No se está vendiendo nada</xalert> 
     </service> 

     <service name="pd_today_sales00001" caption="Importe" desc="Importe ventas del día" type="3" detail="1"> 
      <xvalue>0,00</xvalue> 
      <xcolor>2</xcolor> 
      <xalert>No estamos recaudando nada</xalert> 
     </service> 
    </widget> 
</widgets> 

加載的XML,並準備嘗試過,但我不能得到你所需要

的各個領域,我需要:

  • ID ,
  • 控件的標題屬性,
  • 每個控件的服務,
  • 服務的caption屬性,
  • x值,
  • xcolor和xalert,
  • 每個服務

我可以得到所有的部件,像這樣的:(我認爲兩種:EmployeesEmployee

[XmlRoot("widgets")] 
public class Employees 
{ 
    [XmlElement("widget")] 
    public ObservableCollection <Employee> Coleccion { get; set; } 
} 


public class Employee 
{ 
    [XmlAttribute("caption")] 
    public string nombreWidget { get; set; } 
} 

但不喜歡把自己內部的每個插件各自的服務(服務屬性),和這些x值,xcolor和xalert內

+1

您是否考慮過使用Linq轉XML或XPATH?還是你必須使用'XmlSerializer'? – mipe34

+0

我正在使用LINQ to XML,因爲不幸的是XPath目前不支持,並且LINQ沒有訪問所有標籤 – user1909412

回答

0

LinqToXml解決方案:

var xml = XDocument.Parse(Resource1.XMLFile1).Root; 
var parsed = new { 
        Id = xml.Element("id").Value, 
        Widgets = xml.Elements("widget") 
            .Select(w => new 
            { 
             Caption = w.Attribute("caption").Value, 
             Services = w.Elements("service").Select(s => new 
             { 
              Caption = s.Attribute("caption").Value, 
              XColor = s.Element("xcolor").Value, 
              XValue = s.Element("xvalue").Value, 
              XAlert = s.Element("xalert") != null ? s.Element("xalert").Value : null 
             }).ToList() 
            }).ToList() 
       }; 

它將創建代表您的inpout XML的匿名對象。您可以輕鬆地將我的代碼中的匿名對象替換爲您的真實域對象(Employees等)。

+1

完美的解決方案,謝謝! – user1909412

0

你應該使用XPath

using System.Xml.XPath; 

然後做這樣的事情:

XPathNavigator nav; 
XPathDocument docNav; 
XPathNodeIterator NodeIter; 
String strExpression; 

// Open the XML. 
docNav = new XPathDocument(@"c:\books.xml"); 

// Create a navigator to query with XPath. 
nav = docNav.CreateNavigator(); 

// Find the average cost of a book. 
// This expression uses standard XPath syntax. 
strExpression = "sum(/bookstore/book/price) div count(/bookstore/book/price)"; 

有關的一切,可以使用XPath考慮實現的更多信息: https://developer.mozilla.org/en/docs/XPath

+0

我正在使用Window Phone應用程序,因爲我需要使用xpath和linq。不幸的是xpath目前不支持。 – user1909412