2012-12-01 128 views
2

我有這個xml文件。我試圖獲取特定servername屬性的所有dbistance。 因爲我想添加在列表框級聯 的結果,這樣的默認各dbistance信息組 - DBCATALOG - 用戶名 - 密碼 - 1433 討好我......開始LINQ恨:)查詢linq到xml

<?xml version="1.0" encoding="utf-8" ?> 
<root> 
    <server servername="SRV01"> 
    <dbistance> 
     <istancename>DEFAULT</istancename> 
     <catalog>DBCATALOG01</catalog> 
     <username>USERNAME</username> 
     <password>PASSWORD</password> 
     <port>1433</port> 
    </dbistance> 
    <dbistance> 
     <istancename>DEFAULT</istancename> 
     <catalog>DBCATALOG02</catalog> 
     <username>USERNAME</username> 
     <password>PASSWORD</password> 
     <port>1433</port> 
    </dbistance> 
    </server> 

    <server servername="SRV02"> 
    <dbistance> 
     <istancename>DEFAULT</istancename> 
     <catalog>DBCATALOG01</catalog> 
     <username>USERNAME</username> 
     <password>PASSWORD</password> 
     <port>1433</port> 
    </dbistance> 
    </server> 
</root> 

回答

1

試試這個

var doc = XDocument.Load(new StringReader(xml)); 
var result = doc.Root 
       .Descendants("dbistance") 
       .Select(elem => elem.Descendants() 
            .Select(elem2 => elem2.Value) 
            .Aggregate((current, next) => current + " - " + next)); 
+1

+1非標準方法 –

1

我想拆分XML解析和結果格式化爲兩個操作。但這是一個單一的查詢:

XDocument xdoc = XDocument.Load(path_to_xml); 
string serverName = "SRV01"; 
IEnumerable<string> dbInstances = 
      xdoc.Descendants("server") 
       .Where(s => (string)s.Attribute("servrname") == serverName) 
       .Descendants("dbinstance") 
       .Select(db => String.Format("{0} - {1} - {2} - {3} - {4}", 
        (string)db.Element("istancename"), 
        (string)db.Element("catalog"), 
        (string)db.Element("username"), 
        (string)db.Element("password"), 
         (int)db.Element("port"))); 

順便說一句,你有錯字istancename標籤。


想想也創建類,將保存數據並做格式化你:

public class DbInstance 
{ 
    public string InstanceName { get; set; } 
    public string Catalog { get; set; } 
    public string UserName { get; set; } 
    public string Password { get; set; } 
    public int Port { get; set; } 

    public override ToString() 
    { 
     return String.Format("{0} - {1} - {2} - {3} - {4}", 
        InstanceName, Catalog, UserName, Password, Port)); 
    } 
} 

解析XML(您可以在單獨的方法做到這一點,這將返回dbinstance具備對象的集合):

XDocument xdoc = XDocument.Load(path_to_xml); 
string serverName = "SRV01"; 
IEnumerable<DbInstance> dbInstances = 
      xdoc.Descendants("server") 
       .Where(s => (string)s.Attribute("servrname") == serverName) 
       .Descendants("dbinstance") 
       .Select(db => new DbInstance() { 
        InstanceName = (string)db.Element("istancename"), 
        Catalog = (string)db.Element("catalog"), 
        UserName = (string)db.Element("username"), 
        Password = (string)db.Element("password"), 
        Port = (int)db.Element("port") }); 

而只是分配給列表框實例(重寫ToString方法將做的工作):

listBox.DataSource = dbInstances; 
+1

+1詳細答案 –

+0

@RomanPekar謝謝! –

+0

我也喜歡你的答案保證給出元素的正確順序,而我的取決於節點的順序。 –