如何在vb.net中缩短此代码?

时间:2014-01-23 10:03:34

标签: xml vb.net

在我的代码中,我希望缩短我使用的每个部分“.element(”Landlord)“和”.element(“Others”)。我的意思是我想用任何其他语句或循环来分解那些重复的部分

我的xml文件是:

<root>
  <House Code="1">
    <Landlord>
      <Name>Alireza</Name>
      <Phone>012345</Phone>
    </Landlord>
    <Others>
      <Remarks>---</Remarks>
      <Status>AV</Status>
    </Others>
  </House>
</root>

这是我的代码:

    Dim houseEle As IEnumerable(Of XElement) = _
          From _codeNo In RHEle...<House> _
          Where _codeNo.@Code = "1"
          Select _codeNo


    For Each ele In houseEle
        Dim elName As String = ele.Element("Landlord").Element("Name").Value
        txtOwner.Text = elName

        Dim elPhone As String = ele.Element("Landlord").Element("Phone").Value
        txtPhone.Text = elPhone


        Dim elRemark As String = ele.Element("Others").Element("Remarks").Value
        txtDescribe.Text = elRemark

        Dim elRs = ele.Element("Others").Element("Status").Value
        txtStatus.Text = elRs

    Next

2 个答案:

答案 0 :(得分:3)

For Each ele In houseEle

  Dim landlord = ele.Element("Landlord")  

  txtOwner.Text = landlord.Element("Name").Value

  txtPhone.Text = landlord.Element("Phone").Value

  'etc

  Dim others = ele.Element("Others")

  'etc

应该这样做。

答案 1 :(得分:3)

为什么不简单地使用临时变量?

 For Each ele In houseEle
    Dim landlordElement = ele.Element("Landlord")
    txtOwner.Text = landlordElement.Element("Name").Value
    txtPhone.Text = landlordElement.Element("Phone").Value
    txtMobile.Text = landlordElement.Element("Mobile").Value

    Dim othersElement = ele.Element("Others")
    txtDescribe.Text = othersElement.Element("Remarks").Value
    txtStatus.Text = othersElement.Element("Status").Value
Next

我还建议修改你的命名约定。例如:

For Each houseElement In houseElements

看起来好多了。

如果您想进一步缩短它,请创建一个Dictionary,它将XML元素名称映射到控件并进行迭代。因此,在类中创建它(使其可重用)

Dim mapping As Dictionary(Of String, Control) = New Dictionary(Of String, Control)() From
{
    {"Name", txtOwner},
    {"Phone", txtPhone},
    {"Mobile", txtMobile}
}

然后只使用此映射:

mapping.Select(Function(p) p.Value.Text = landlordElement.Element(p.Key).Value)