在 C# 中使用 XDocument 构建 XML

Building XML using XDocument in C#

目标是在 C# 中构建以下 XML,通过 StreamWriter 将其写出并将其作为 HTTP 请求的一部分传递。

<WEB_INTEGRATION_REQUEST> 
  <HTTP_HEADER_INFORMATION>
    <DEFINED_HEADERS>
      <HTTP_DEFINED_REQUEST_HEADER>
        <ItemNameType>RequesteDate</ItemNameType>
        <ItemValue>{TIME VALUE}</ItemValue> 
      </HTTP_DEFINED_REQUEST_HEADER>
      <HTTP_DEFINED_REQUEST_HEADER>
        <ItemNameType>AuthorizationValue</ItemNameType>
        <ItemValue>{EncryptedCredentials}</ItemValue> 
      </HTTP_DEFINED_REQUEST_HEADER>
    </DEFINED_HEADERS>
  </HTTP_HEADER_INFORMATION>
  <COLLABORATION>
    <TransactionID>0-A</TransactionID>
    <SequenceID>999</SequenceID>
  </COLLABORATION>
</WEB_INTEGRATION_REQUEST>

编写此 XML 的最佳方法是什么?我尝试使用 XDocument(如下所示),但在 XElementsXAttributes:

中感到困惑
private string BuildXML(string encodedCredentials)
{
    XDocument requestXMl = new XDocument( 
        new XElement("WEB_INTEGRATION_REQUEST",
            new XElement("HTTP_HEADER_INFORMATION",
                new XElement("DEFINED_HEADERS",
                    new XElement("HTTP_DEFINED_REQUEST_HEADER",
                            new XElement("ItemNameType","RequestDate"),
                            new XElement("ItemValue",_currentTime)
                                ),    
                        new XElement("HTTP_DEFINED_REQUEST_HEADER",
                            new XElement("ItemNameType","AuthorizationValue"),
                            new XElement("ItemValue",encodedCredentials)
                                )  
                              )
                           ),
            new XElement("COLLABORATION" ,
                new XElement("TransactionID", _transactionID),
                new XElement("SequenceID",_sequenceNumber)
                        )
                    )
            );

您可以选择创建一个 class 并将其序列化为 XML。在您的成员中使用 XmlElement 属性来匹配您的标签名称,例如 MSDN link.

XDocument requestXMl = new XDocument( 
        new XElement("WEB_INTEGRATION_REQUEST",
            new XElement("HTTP_HEADER_INFORMATION",
                new XElement("DEFINED_HEADERS",
                    new XElement("HTTP_DEFINED_REQUEST_HEADER",
                            new XElement("ItemNameType","RequesteDate"),
                            new XElement("ItemValue",_currentTime)
                                ),    
                        new XElement("HTTP_DEFINED_REQUEST_HEADER",
                            new XElement("ItemNameType","AuthorizationValue"),
                            new XElement("ItemValue",encodedCredentials)
                                )  
                              )
                           ),
            new XElement("COLLABORATION" ,
                new XElement("TransactionID", transactionID),
                new XElement("SequenceID",sequenceID)
                        )
                    )
            );

我就是这样做的。