2012-12-19 35 views
18

Tôi đã xml như sau:Làm thế nào để chuyển đổi XML để từ điển

<?xml version="1.0" encoding="UTF-8"?> 
<root> 
    <data name="LogIn">Log In</data> 
    <data name="Password">Password</data> 
</root> 

Tôi thành công để làm điều đó mà không cần LINQ, bất cứ ai có thể giúp tôi để chuyển đổi đoạn mã sau để LINQ:

using (XmlReader reader = XmlReader.Create(_xml)) 
{ 
    while (reader.Read()) 
    { 
     if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "data") 
     { 
      reader.MoveToAttribute("name"); 
      string key = reader.Value; 
      reader.MoveToContent(); 
      string value = reader.ReadElementContentAsString(); 
      _dictionary.Add(key, value); 
     } 
    } 
    reader.Close(); 
} 
+6

Mật khẩu văn bản thuần túy trong tệp XML ... –

Trả lời

20
var xdoc = XDocument.Load(path_to_xml); 
_dictionary = xdoc.Descendants("data") 
        .ToDictionary(d => (string)d.Attribute("name"), 
           d => (string)d); 
+1

chỉ để rõ ràng XDocument xdoc = XDocument.Load (tên tệp); – Vlad

+0

Tôi nhận được lỗi sau: 'System.Collections.Generic.IEnumerable ' không chứa định nghĩa cho 'ToDictionary' và không có phương pháp mở rộng 'ToDictionary' chấp nhận đối số đầu tiên của loại 'Hệ thống .Collections.Generic.IEnumerable 'có thể được tìm thấy (bạn đang thiếu một chỉ thị sử dụng hoặc tham chiếu assembly?) –

+6

@RamzyAbourafeh Thêm 'using System.Linq;' để bạn có thể sử dụng các phương thức mở rộng LINQ . – ken2k

0
XDocument xdoc = XDocument.Load("test.XML"); 
var query = xdoc.Descendants("root") 
       .Elements() 
       .ToDictionary(r => r.Attribute("name").Value, 
          r => r.Value); 

Hãy nhớ bao gồm:

using System.Linq; 
using System.Xml.Linq; 
0

Đây là câu hỏi cũ, nhưng trong trường hợp ai đó gặp một số 'Typed' xml (ví dụ: từ tệp SharedPreference của ứng dụng android), bạn có thể xử lý như sau: Đây là mẫu xml tôi lấy từ Instagram ứng dụng.

<?xml version='1.0' encoding='utf-8' standalone='yes' ?> 
<map> 
<boolean name="pinnable_stickers" value="false" /> 
<string name="phone_number">+254711339900</string> 
<int name="score" value="0" /> 
<string name="subscription_list">[]</string> 
<long name="last_address_book_updated_timestamp" value="1499326818875" /> 
//...other properties 
</map> 

Lưu ý sự không thống nhất trong thuộc tính giá trị. Một số trường (ví dụ: loại string) không được xác định rõ ràng.

var elements = XElement.Load(filePath) 
.Elements() 
.ToList(); 
var dict = new Dictionary<string, string>();  
var _dict = elements.ToDictionary(key => key.Attribute("name").Value, 
         val => val.Attribute("value") != null ? 
         val.Attribute("value").Value : val.Value); 
Các vấn đề liên quan