[英]LINQ to XML: don't get XElement
it should be easy but I don't really see my fault. 这应该很容易,但我看不出我的错。
public static void Edit(string old, string neew, string type)
{
XElement root = XElement.Load(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Xml.xml");
switch (type)
{
case "Customer":
XElement name = root.Descendants("Data").Descendants("Customer")
.Where(x => x.Element("Name").Value.ToString() == old)
.FirstOrDefault();
name.SetElementValue("Name", neew);
break;
XElement name returns null, so I get a NullReferenceException. XElement名称返回null,因此我得到了NullReferenceException。 But I don't know, why it only returns null.
但我不知道为什么它只返回null。
This is my Xml structure: 这是我的Xml结构:
<Data>
<Customer>
<Name>CustomerA</Name>
<IP>888.888.888.888</IP>
<UserLogin>auser</UserLogin>
<UserPw>apwd</UserPw>
</Customer>
<Customer>
<Name>CustomerB</Name>
<IP>102.16.70.181</IP>
<UserLogin>buser</UserLogin>
<UserPw>bpwd</UserPw>
</Customer>
</Data>
Maybe someone could open my eyes and help me? 也许有人可以睁开眼睛帮助我? Or give a hint?
或给出提示?
it seems Data
is already your root element. 看来
Data
已经是您的根本要素。 You can use root.Elements("Customer")
or root.Descendants("Customer")
instead. 您可以改用
root.Elements("Customer")
或root.Descendants("Customer")
。
Apart from that XElement.Value
property is of type string
, so you don't need to call ToString
on it.Also you may consider using explicit casts like (string)x.Element("Name") == old
to avoid exceptions if the elements isn't found. 除此之外,
XElement.Value
属性的类型为string
,因此您无需在其上调用ToString
。此外,您还可以考虑使用显式强制转换,例如(string)x.Element("Name") == old
以避免出现异常找不到元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.