简体   繁体   中英

c# LINQ to XML - XDocument

Just trying to read a simple XML doc in using XDocument class. The document is read, but I'm struggling mapping my OperationConfig to the XML?

var xml = XDocument.Load(path);
var query = xml.Root.Elements("configaccount")
    .Select(o => new OperationConfig()
    {
        AccountName = o.Attribute("accountname").Value,
        Email = o.Attribute("email").Value
    });

The XML:

<?xml version="1.0" encoding="UTF-8"?>
    <config>
        <configaccount>
            <accountname>
                BusinessName
            </accountname>
            <email>
                aa@domain.com
            </email>
        </configaccount>
    </Config>

Not sure what I've missed as I'm retuning null?

You need to retrive Descendants node by name from xml. Also "accountname" and "email" is not an attributes, its an Element of XML. Attributes are inside element.

Replace your query

 var query = xml.Descendants("configaccount")
        .Select(o => new OperationConfig
        {
            AccountName = o.Element("accountname").Value,
            Email = o.Element("email").Value
        });

Hope this help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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