我使用以下查询将XML转换为结构。如果一个元素不存在,我将如何在以下查询中容纳它(ClntCde将始终存在,但有可能Title不存在)
ClientTbl ClientData = clientNode.Select(x => new ClientTbl
{
ClientCode = x.Elements().Where(e => e.Name.LocalName == "ClntCde").FirstOrDefault().Value,
//Title = x.Elements().Where(e => e.Name.LocalName == "Title").ToString(),
//Title = x.Elements().Where(e => e.Name.LocalName == "Title").FirstOrDefault().Value,
//Title = x.Elements("Title").FirstOrDefault().Value,
}
).First();
XML:
<Client xmlns="http://www.website.co.za/namespace">
<ClntCde>0000013</ClntCde>
<Surname>Account Holder Surname</Surname>
<Address>
<Addr1>.</Addr1>
<Addr2>.</Addr2>
<Addr3>.</Addr3>
<Addr4>.</Addr4>
<PostCde>2000</PostCde>
</Address>
<ClntAccTyp>A</ClntAccTyp>
<ElecInd>NO</ElecInd>
<Lang>ENG</Lang>
</Client>
答案 0 :(得分:3)
您可以使用DefaultIfEmpty("")
:
ClientCode = x.Elements()
.Where(e => e.Name.LocalName == "ClntCde")
.Select(e => e.Value)
.DefaultIfEmpty("")
.First(),
Title = x.Elements()
.Where(e => e.Name.LocalName == "Title")
.Select(e => e.Value)
.DefaultIfEmpty("")
.First(),
// ...
请注意,如果您自己提供默认值,则...OrDefault
是多余的。调用First
或Single
(仍然可以抛出多个元素)是安全的,因为它永远不会为空。
答案 1 :(得分:1)
Title = (String)x.Elements()
.Where(e => e.Name.LocalName == "Title")
.Single();
或强>
声明命名空间
XNamespace ns="http://www.website.co.za/namespace";
并参考
Title = (String)x.Element(ns+"Title")
答案 2 :(得分:0)
尝试:
Title = x.Elements()
.Where(e => e.Name.LocalName == "Title")
.Select(e => e.Value)
.FirstOrDefault() ?? string.Empty;
答案 3 :(得分:0)
var ns = clientNode.GetDefaultNamespace();
ClientTbl ClientData = clientNode.Select(x => new ClientTbl
{
ClientCode = (string)x.Element(ns + "ClntCde") ?? string.Empty,
Title = (string)x.Element(ns + "Title") ?? string.Empty,
}
).First();
更新1:添加默认命名空间
更新2:如果元素不存在,则添加空白字符串
答案 4 :(得分:0)
使用此XML Library,您可以直接引用每个元素,如果不存在,则提供默认值:
ClientTbl ClientData = clientNode.Select(x => new ClientTbl
{
ClientCode = x.Get("ClntCde", "defaultCode"),
Title = x.Get("Title", "defaultTitle"),
Addr1 = x.Get("Address/Addr1", "addr1 default"),
// and/or
Address = x.GetElement("Address") // Creates the Address node if doesn't exist
.Select(a => new
{
Addr1 = a.Get("Addr1", "addr1 default"),
// etc
})
});
默认值是特定于类型的。如果您的代码始终是数字,则可以使用数字默认值,它将是该类型。 Get
也处理名称空间。
Get has the syntax(在这种情况下):
T Get<T>(string name, T defaultValue);