XML XElement构建一个xml文档

时间:2015-01-12 12:11:50

标签: c# xml

您好我是XML构建的新手,我以前基本上没有使用它,我总是喜欢json。

我有一个解决方案,我只使用字符串并转换为XML对象,但我怎样才能使用XElement类?

这是文件:

<?xml version="1.0" encoding="utf-8"?>
 <requestblock version="3.67">
    <alias>ALIAS</alias>
    <request type="AUTH"> 
       <operation> 
          <sitereference>test12345</sitereference> 
          <accounttypedescription>TEST</accounttypedescription> 
          <parenttransactionreference>12-3-4567</parenttransactionreference> 
       </operation> 
       <merchant> 
          <orderreference>Example recurring auth</orderreference>
       </merchant> 
       <customer> </customer> 
       <billing> 
          <amount currencycode="GBP">1234</amount> 
          <subscription type="TEST">
             <number>1</number>
          </subscription> 
       </billing> 
       <settlement/>
    </request> 
 </requestblock>

我已经有了这样的部分代码:

       XElement address =
            new XElement("alias", "TEST",
            new XElement("request", new XAttribute("type", "AUTH"),
            new XElement("City", "Mercer Island"),
            new XElement("State", "WA"),
            new XElement("Postal", "68042")
       ));

但我的别名有问题,因为别名在所有元素之后关闭,而不是以相同的表示法:

<alias>TEST
    <request type="AUTH">
        <City>Mercer Island</City>
        <State>WA</State>
        <Postal>68042</Postal>
    </request>
</alias>

正如您所看到的,符号就是问题。

1 个答案:

答案 0 :(得分:1)

您将别名设置为根元素,该元素应为requestblock。如果你从这个请求块开始:

XElement address =
       new XElement("requestblock", new XAttribute("version",3.67),
       new XElement("alias", "TEST"),
       new XElement("request", new XAttribute("type", "AUTH"),
       new XElement("City", "Mercer Island"),
       new XElement("State", "WA"),
       new XElement("Postal", "68042")

它会给你

<requestblock version="3.67">
   <alias>TEST</alias>
   <request type="AUTH">
      <City>Mercer Island</City>
      <State>WA</State>
      <Postal>68042</Postal>
   </request>
</requestblock>