使用XElement select语句添加许多元素

时间:2011-05-18 22:02:25

标签: c# xml string linq-to-xml

输入:

"CustomerName Details 121.11.2222 Address-Line1,City,State 36,EU \r
Customer1 SomeDetails 911.911.911 ABCD Street, Some Lane, Some City, Some State  50,USA \n
"

我想生成这样的XML:

<Customers>
<Customer>
<Name>CustomerName</Name>
<Details>Details</Details>
<Phone>121.11.2222</Phone>
<AddressDetails>
 <Address>Address-Line1</Address>
 <Address>City</Address>
 <Address>State</Address>
</AddressDetails> 
<PersonalDetails>
 <Age>36</Age>
 <Nation>EU</Nation>
</PersonalDetails>
</Customer>

<Customer>
....
</Customer>
</Customers> 

好处是输入字符串始终遵循所有行集的相同格式。

使用LINQ尝试这样的事情,当我尝试在同一个选择下创建多个XElement时,我会陷入困境(见下文):

string inputString ="CustomerName Details 121.11.2222 Address-Line1,City,State 36,EU \r    Customer1 SomeDetails 911.911.911 ABCD Street, Some Lane, Some City, Some State  50,USA \n    ";
string[] inputRow = inputString.Split('\n');

 var root = new XElement("Customers",

    from customerRowSet in inputRow  
    select new XElement("Customer",    
        from column in customerRowSet.Split('\t') //Assume columns are tab seperated
       select 
           new XElement("Name", column), 
      //  new XElement("Details", column[1]), Need to add to XML here, but error is thrown on attempt


        from commafilters in customerRowSet.Split(',')
        select new XElement("AddressDetails", commafilters)  //Not sure how to filter out Address[x] seperate from PersonalDetails[y] as both come in comma-seperated

      ));

执行此操作的其他任何技术,如字符串操作或Regex?

1 个答案:

答案 0 :(得分:2)

您不希望将LINQ用于列,因为您希望以不同方式处理每个列。你能做的就是这样:

var root = new XElement("Customers",
    from customerRowSet in inputRow
    let columns = customerRowSet.Split('\t') //Assume columns are tab seperated
    select new XElement("Customer",
        new XElement("Name", columns[0]),
        new XElement("Details", columns[1]),
        new XElement("Phone", columns[2]),
        new XElement("Address",
            from commafilters in columns[3].Split(',')
            select new XElement("AddressDetails", commafilters.TrimStart())
    )));

生成以下XML:

<Customers>
  <Customer>
    <Name>CustomerName</Name>
    <Details>Details</Details>
    <Phone>121.11.2222</Phone>
    <Address>
      <AddressDetails>Address-Line1</AddressDetails>
      <AddressDetails>City</AddressDetails>
      <AddressDetails>State</AddressDetails>
    </Address>
  </Customer>
  <Customer>
    <Name>Customer1</Name>
    <Details>SomeDetails</Details>
    <Phone>911.911.911</Phone>
    <Address>
      <AddressDetails>ABCD Street</AddressDetails>
      <AddressDetails>Some Lane</AddressDetails>
      <AddressDetails>Some City</AddressDetails>
      <AddressDetails>Some State</AddressDetails>
    </Address>
  </Customer>
</Customers>