Linq对XML非常新,并且在这个问题上摸不着头脑。我正在使用Xdocument创建一个XML文档,从数据库中获取一些数据然后为每个语句使用a并添加每个数据行,即
Dim MyCustomers As IQueryable(Of Customer) = GetCUstomers
Dim XDoc As XDocument = <?xml version="1.0" encoding="UTF-8" standalone="yes"?<Customers></Customers>
For Each c As Customer In MyCustomers
Xdoc.Root.Add(<CustomerID=<%= c.Id %>
<FirstName><%= c.Name %></FirstName>
<Surname><%= c.Surname %></Surname>
Next
我想有一个If语句,所以如果Surname为空我想要完全删除该元素。
因此,如果客户的姓氏存在,那么XML就是
<CustomerID=123>
<FirstName>Name</FirstName>
<Surname>Surname></Surname>
如果不是
<CustomerID=123>
<FirstName>Name</FirstName>
我尝试过使用
<%= If (string.IsnullEmpty(c.Surname) Then %>
和其他组合,但无论我尝试什么,我得到一个语法错误。我搜索过MSDN,大多数示例都是指获取节点但不是根据条件在XML文件中创建节点/元素。我真的迷失了如何接近这个?
有人可以帮忙吗?
答案 0 :(得分:1)
我认为可能有些代码出现乱码 - 有一些无效的XML元素,例如<CustomerID=123>
,可能应该是<Customer ID=123>
。也就是说,以下(在LINQPad中运行)可以满足您的需求,我希望您可以根据自己的代码进行调整。
Sub Main
Dim MyCustomers = New List(Of Customer)() From {
New Customer() With { .ID = 1, .Name = "Cust1", .Surname = "Surn1" },
New Customer() With { .ID = 2, .Name = "Cust2" },
New Customer() With { .ID = 3, .Name = "Cust3", .Surname = "Surn3" },
New Customer() With { .ID = 4, .Name = "Cust4" }
}
Dim Xdoc = <?xml version="1.0" encoding="UTF-8" standalone="yes"?><Customers></Customers>
For Each c As Customer In MyCustomers
Dim cust =
<Customer ID=<%= c.Id %>>
<FirstName><%= c.Name %></FirstName>
</Customer>
If c.Surname IsNot Nothing Then
cust.Add(<Surname><%= c.Surname %></Surname>)
End If
Xdoc.Root.Add(cust)
Next
Xdoc.Dump()
End Sub
' Define other methods and classes here
Public Class Customer
Public Property ID As Integer
Public Property Name As String
Public Property Surname As String
End Class
<强>更新强>
以上是上述循环,但使用嵌入式LINQ查询有选择地添加<Surname>
元素。就个人而言,我发现上面的逻辑更具可读性,但两者都产生相同的输出。
For Each c As Customer In MyCustomers
Xdoc.Root.Add(
<Customer ID=<%= c.Id %>>
<FirstName><%= c.Name %></FirstName>
<%= From sn In New String() { c.Surname }
Where sn IsNot Nothing
Select <Surname><%= sn %></Surname>
%>
</Customer>
)
Next
这是输出:
<Customers>
<Customer ID="1">
<FirstName>Cust1</FirstName>
<Surname>Surn1</Surname>
</Customer>
<Customer ID="2">
<FirstName>Cust2</FirstName>
</Customer>
<Customer ID="3">
<FirstName>Cust3</FirstName>
<Surname>Surn3</Surname>
</Customer>
<Customer ID="4">
<FirstName>Cust4</FirstName>
</Customer>
</Customers>