具有相同名称元素的XML

本文关键字:元素 XML | 更新日期: 2023-09-27 18:16:33

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

    <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;

具有相同名称元素的XML

您可能希望使用它的索引访问每个<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;

您可以迭代它们,使它们按顺序呈现:

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

或按索引;

var lines = StructuredAddress.Elements("AddressLine").ToList();
lines[0].Value = "...";
相关文章: