LINQtoXML機能構築がどのように機能するかを理解しようとしています。
次のサンプルXMLがあります。
string xml = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<People>
<Person firstName=""John"" lastName=""Doe"">
<ContactDetails>
<EmailAddress>john@unknown.com</EmailAddress>
</ContactDetails>
</Person>
<Person firstName=""Jane"" lastName=""Doe"">
<ContactDetails>
<EmailAddress>jane@unknown.com</EmailAddress>
<PhoneNumber>001122334455</PhoneNumber>
</ContactDetails>
</Person>
</People>";
タグにIsMale
属性を追加し、存在しない場合はaを追加して、このXMLを変更しようとしています。Person
PhoneNumber
手続き型コードを使用すると、このコードを簡単に記述できます。
XElement root = XElement.Parse(xml);
foreach (XElement p in root.Descendants("Person"))
{
string name = (string)p.Attribute("firstName") + (string)p.Attribute("lastName");
p.Add(new XAttribute("IsMale", IsMale(name)));
XElement contactDetails = p.Element("ContactDetails");
if (!contactDetails.Descendants("PhoneNumber").Any())
{
contactDetails.Add(new XElement("PhoneNumber", "001122334455"));
}
}
しかし、MSDNのドキュメントには、FunctionalConstructionの保守がより簡単で優れている必要があると記載されています。そこで、FunctionalConstructionで同じサンプルを書いてみました。
XElement root = XElement.Parse(xml);
XElement newTree = new XElement("People",
from p in root.Descendants("Person")
let name = (string)p.Attribute("firstName") + (string)p.Attribute("lastName")
let contactDetails = p.Element("ContactDetails")
select new XElement("Person",
new XAttribute("IsMale", IsMale(name)),
p.Attributes(),
new XElement("ContactDetails",
contactDetails.Element("EmailAddress"),
contactDetails.Element("PhoneNumber") ?? new XElement("PhoneNumber", "1122334455")
)));
私かもしれませんが、このコードの方が読みやすいとは思いません。
機能構造を改善するにはどうすればよいですか?このコードを書くためのより良い方法はありますか?