繁体   English   中英

使用 C# 读取 XML 文件中节点的 ID

[英]Reading the ID of an Node in XML-File using C#

我在 C# 中读取 XML 文件中的变量时遇到问题。

我有以下 XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<list xmlns:xsd=...> 
    <row id="2b7bed1a-bd72-4e83-9b69-26c05cce6379">
        <hostname>TestName1</hostname> 
        <outputs> 
            <outputId>HL7 Output</outputId> 
        </outputs> 
    </row>
    
    <row ...

    </row>
</list>

我在这里尝试编写一个代码,它读取 XML 文件并使用循环获取每个主机名的 ID。

我已经编写了以下部分,它加载了 xml 文件。 有人可以帮我完成这个吗?

   var xmlFile = @"C:\Users\vosoughi-m\Desktop\output_mapping.xml";
   var doc = new XmlDocument();
   doc.Load(xmlFile);  

提前致谢

编辑:

我想要以下 output:

主机名:TestName1

编号:2b7bed1a-hd72-4e83-9b69-66c05cce6379


主机名:TestName2

编号:ce4372d3-453e-4ed8-ba60-6694a2680c24

...

使用 xml linq:

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


namespace ConsoleApplication21
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";

        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            var results = doc.Descendants("row")
                .Select(x => new { id = (string)x.Attribute("id"), hostname = (string)x.Element("hostname") }).ToList();
        }
 
    }
 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM