目标是在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
(如下所示),但在XElements
和XAttributes
中感到困惑:
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)
)
)
);
答案 0 :(得分:1)
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)
)
)
);
多数民众赞成我是如何做到的。
答案 1 :(得分:0)
您可以选择创建一个类并将其序列化为XML。在您的成员中使用XmlElement属性来匹配您的标记名称,例如此MSDN link。