C# 使用Linq到Xml的空引用

C# 使用Linq到Xml的空引用,c#,xml,linq,linq-to-xml,C#,Xml,Linq,Linq To Xml,我正在制作国家、州的下拉列表 例如:对于特定的国家,我将从XML文件中读取该国的州,下面是我的代码 protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { string st = (DropDownList1.SelectedIndex).ToString(); XDocument main = XDocument.Load((Server.Ma

我正在制作国家、州的下拉列表

例如:对于特定的国家,我将从XML文件中读取该国的州,下面是我的代码

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
         string  st = (DropDownList1.SelectedIndex).ToString();

         XDocument main = XDocument.Load((Server.MapPath(@"XMLFile1.xml")));


    var query = from user in main.Descendants("country")
            where st == user.Element("state").Value --//i am getting an error here like object 
            select user;                                reference not set to an instance object

    DropDownList2.DataSource = query;
    DropDownList2.DataBind();   

    }

OP的XML(Chuck评论中提供的链接):

您需要发布您的XML,但当前的问题是用户没有子元素
.Element(“state”)
,因此您试图为该用户引用
null.Value

此Xml库可以帮助您:

使用以下代码,您可以获得所需的物品

string country = "Sri Lanka";
XElement root = XElement.Load(Server.MapPath(@"XMLFile1.xml"));
XElement xcountry = root.XPathElement("//country[.={0}]", country);

然后


然后您可能会将状态绑定为数据源。

根据经验,您最好使用“SelectMany”解决方案来避免检查节点的存在

 var query = from user in main.Descendants("country")
            from state in user.Elements("state")
            where state.Value == st
            select user;        
如果节点不存在,则users.Elements(“state”)将为空(非null),因此用户节点将不包括在where子句中

100%纯Linq,无默认值

编辑:从Chuck的回答评论中的xml形状获取新信息,请求可能是

 var query = from user in main.Descendants("country")
            from state in user.Elements("state")
            from text in state.Elements("text")
            where text.Value == st
            select user;        

编辑2:我的错,xml没有完全分层

如果您在xml文件中使用名称空间,则以下内容可能会对您有所帮助:

XNamespace ns = "url";// the url is the namespace path for your namespace
var query = from user in main.Descendants("country")
            from state in user.Elements("state")
            where state.Value == "st"
            select user; 

如何在此处输入我的xml?将其添加到您的帖子中,单击帖子底部的灰色
编辑
链接。我无法添加xml文件,它显示了一些错误。您可以检查我的xml,与此链接中的相同@CédricRup这些不是子节点,它们是以下节点。恶心@user1435482您希望查询返回的是什么,州列表还是拥有该州的国家?Rup我已经尝试了您的代码,但无法在下拉列表中获得相应的州
 var query = from user in main.Descendants("country")
            from state in user.Elements("state")
            from text in state.Elements("text")
            where text.Value == st
            select user;        
XNamespace ns = "url";// the url is the namespace path for your namespace
var query = from user in main.Descendants("country")
            from state in user.Elements("state")
            where state.Value == "st"
            select user;