使用LINQ选择XML节点

时间:2018-05-14 12:34:24

标签: .net xml linq

我正在尝试选择" publishInformation"节点,(特别是" Publish_Date"值)来自以下xml。

<?xml version="1.0" standalone="yes"?>
    <sdnList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <publshInformation>
        <Publish_Date>04/06/2018</Publish_Date>
        <Record_Count>6297</Record_Count>
    </publshInformation>
    <sdnEntry>
        <uid>36</uid>
        <lastName>TestLastName</lastName>
        <sdnType>Entity</sdnType>
        <addressList>
          <address>
             <uid>25</uid>
             <city>TestCity</city>
             <country>TestCountry</country>
          </address>
        </addressList>
    </sdnEntry>
    </sdnList>

我的所有尝试都获得了空结果,我不确定我缺少什么。以下是我最近的尝试。

XElement root = XElement.Load(model.InputStream);
XElement publishInformation = root.Descendants("sdnList")
                    .Descendants("publshInformation")
                    .SingleOrDefault();

使用JohnyL的建议代码如下。

string xmlstring;
using (StreamReader reader = new StreamReader(model.OfacXml.InputStream))
{
    xmlstring = reader.ReadToEnd();
}

var xml = XElement.Parse(xmlstring);
var dates = xml.Elements("publshInformation").Select(pi => 
    pi.Element("Publish_Date").Value);

我仍然在使用此代码的日期中获取null。

1 个答案:

答案 0 :(得分:1)

var text = 
    @"<?xml version='1.0' standalone='yes'?>
        <sdnList xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>
            <publshInformation>
                <Publish_Date>04/06/2018</Publish_Date>
                <Record_Count>6297</Record_Count>
            </publshInformation>
            <sdnEntry>
                <uid>36</uid>
                <lastName>TestLastName</lastName>
                <sdnType>Entity</sdnType>
                <addressList>
                    <address>
                        <uid>25</uid>
                        <city>TestCity</city>
                        <country>TestCountry</country>
                    </address>
                </addressList>
            </sdnEntry>
        </sdnList>";

var xml = XElement.Parse(text);
var dates = xml.Elements("publshInformation").Select(pi => pi.Element("Publish_Date").Value);
dates.ToList().ForEach(WriteLine);

如果您想使用XDocument代替XElement

var xml = XDocument.Parse(text);
var dates = xml.Element("sdnList")
               .Elements("publshInformation")
               .Select(pi => pi.Element("Publish_Date").Value);