簡體   English   中英

C#XML-一次讀取多個元素

[英]C# XML - reading multiple elements at once

我有這個xml文件:

<?xml version="1.0" ?>
<object>
    <name>Sphere</name>
    <material>Steel</material>
    <device Id="01">
        <model>Model 1</model>
        <color>Red</color>
    </device>
    <device Id="02">
        <model>Model 2</model>
        <color>Blue</color>
    </device>
</object>

我希望能夠在for循環中讀取每個設備的型號和顏色。 我的代碼一次只能讀取一個值(模型或值),而且我必須循環兩次。

我希望應該有一個更優雅的解決方案。

var xDoc = XDocument.Load(@"C:\_Projects\AProjectsCS\XML_Tutorial\Sample.xml");

IEnumerable<XElement> list1 = xDoc.Root.Descendants("model");  
IEnumerable<XElement> list2 = xDoc.XPathSelectElements("//color");  

foreach (XElement el in list1)
    Console.WriteLine(el.Value);

foreach (XElement el in list2)
    Console.WriteLine(el.Value);

謝謝,尼克

只需從每個設備元素中選擇模型和顏色元素值(您可以使用以下匿名類型,也可以創建自定義Device類來保存此數據):

var xDoc = XDocument.Load(@"C:\_Projects\AProjectsCS\XML_Tutorial\Sample.xml");
var devices = from d in xDoc.Root.Elements("device")
              select new {
                  Model = (string)d.Element("model"),
                  Color = (string)d.Element("color")
              };

foreach(var device in devices)
{
    Console.WriteLine(device.Model);
    Console.WriteLine(device.Color);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM