具有相同名称的元素的XML

时间:2014-08-05 14:03:07

标签: c# .net xml

如何编辑每个地址行中的数据,因为它们都具有相同的名称?

    <StructuredAddress>
      <AddressLine></AddressLine>
      <AddressLine></AddressLine>
      <AddressLine></AddressLine>
    </StructuredAddress>

到目前为止,我的代码无法正常工作。如何单独隔离每个AddressLine并插入适当的数据?

     XElement StructuredAddress = PatientAddress.Descendants("StructuredAddress").First();
     StructuredAddress.Element("AddresLine").Value = cc.address1;
     StructuredAddress.Element("AddresLine").Value = cc.address2;
     StructuredAddress.Element("AddresLine").Value = cc.address3;

2 个答案:

答案 0 :(得分:2)

您可能希望使用它的索引访问每个<AddressLine>

XElement StructuredAddress = PatientAddress.Descendants("StructuredAddress").First();
var address = StructuredAddress.Elements("AddresLine").ToList();
address[0].Value = cc.address1;
address[1].Value = cc.address2;
address[2].Value = cc.address3;

答案 1 :(得分:1)

您可以迭代它们,按顺序显示它们:

foreach (var addressLine in StructuredAddress.Elements("AddressLine"))
{
    addressLine.Value = ...
}

或通过索引;

var lines = StructuredAddress.Elements("AddressLine").ToList();
lines[0].Value = "...";