簡體   English   中英

從 xml 獲取帶有父節點詳細信息的數據

[英]Getting data from xml with parent node details

我有以下 xml 文件

  <Department Name="Electronic">
    <Employee ID="1" Name="John" Address="xyz,abc" />
    <Employee ID="2" Name="Jim" Address="ntg,abc"/>
    <Employee ID="3" Name="Liz" Address="rhx,abc" />
  </Department>
  <Department Name="Computer">
    <Employee ID="1" Name="Tony" Address="mnc,abc"" />
    <Employee ID="2" Name="Tom" Address="abr,abc" />
  </Department>

我想使用 C# 和 linq 以這種形式獲取數據

Electronic, 1 , John
Electronic, 2 , Jim
Electronic, 3 , Liz
Computer,1,Tony
Computer,2,Tom

目前我只通過以下查詢獲取 ID 和名稱,但我也想獲取部門名稱

1 , John
2 , Jim
3 , Liz
1,Tony
2,Tom

    var result1 = str.Elements("Department").Elements("Employee")
        .Select(node => new
        {
            ID = node.Attribute("ID").Value,
            Name = node.Attribute("Name").Value,
        }
        ).ToList();
public class Employee
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Department { get; set; }
}

//Replace doc with your xml element
XElement doc = XElement.Parse(File.ReadAllText("XmlFilePath"));

var employeeList = doc.Elements("Department").Elements("Employee")
            .Select(node => new Employee
            {
                Id = node.Attribute("ID")?.Value,
                Name = node.Attribute("Name")?.Value,
                Address = node.Attribute("Address")?.Value,
                Department = node.Parent?.Attribute("Name")?.Value,
            }).ToList();

嘗試以下給出您正在尋找的 output

using System;
using System.Linq;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace ConsoleApp2
{
    class Program
    {
        const string INPUT_FILENAME = @"c:\temp\test.xml";
        const string OUTPUT_FILENAME = @"c:\temp\test.csv";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(INPUT_FILENAME);
            StreamWriter writer = new StreamWriter(OUTPUT_FILENAME);

            foreach(XElement department in doc.Descendants("Department"))
            {
                string departmentName = (string)department.Attribute("Name");
                foreach(XElement employee in department.Elements("Employee"))
                {
                    string id = (string)employee.Attribute("ID");
                    string employeeName = (string)employee.Attribute("Name");
                    string line = string.Join(",", new string[] { departmentName, id, employeeName });
                    writer.WriteLine(line);
                }
            }

            writer.Flush();
            writer.Close();

        }
    }
}

暫無
暫無

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

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