需要一种动态生成 XML 的方法 [英] Need an approach to generate XML dynamically
问题描述
我有一种情况需要在我的 C# 代码中动态生成以下 XML.例如,XML 文本将是
I have a situation where I need to generate the below XML dynamically in my C# code. For example, the XML text would be
<Envelope>
<Body>
<Login>
<USERNAME>username</USERNAME>
<PASSWORD>Sm@rt123</PASSWORD>
</Login>
</Body>
</Envelope>
要求是将上述 XML 格式作为字符串发送给 API 调用,API 调用会以 XML 格式的字符串形式获得一些响应.
The requirement is to send the above XML format as a string to an API call, which would get some responses as a string in the XML format.
我的问题是上面的例子是一个登录 Api 调用,对于所有的 api 调用,元素 Envelope 和 Body 是相同的,并且基于 api 调用,其他部分就像登录 api 一样,我需要提到一个xml 元素作为 Login 及其属性用户名和密码.
My question is the above example is for a Login Api call, for all the api calls, the elements Envelope and Body are same and based on the api call, the other parts change like for Login api, I need to mention a xml element as Login with its attributes username and password.
到目前为止,我一直在对上述字符串进行硬编码,并尝试测试该功能是否正常工作,但现在我需要自动化为各个不同的 api 调用生成这些标签的过程.我需要知道如何做到这一点,以及这样做的最佳方法是什么.
Till now I have been hardcoding the above string and trying to test if the functionality is working fine, but now I need to automate this process of generating these tags for respective different api calls. I need to know how can this be done and what is the best approach for the same.
推荐答案
我打算建议将序列化作为输出到 XML 的一种简单方法.这是一个简单的例子:
I was going to suggest serialization as a simple way to output to XML. Here's a simple example:
首先创建类
Public Class Login
Public Property USERNAME() As String
Get
Return _USERNAME
End Get
Set(ByVal value As String)
_USERNAME = value
End Set
End Property
Private _USERNAME As String
Public Property PASSWORD() As String
Get
Return _PASSWORD
End Get
Set(ByVal value As String)
_PASSWORD = value
End Set
End Property
Private _PASSWORD As String
End Class
Public Class Body
Public Property Login() As Login
Get
Return _login
End Get
Set(ByVal value As LoginClass)
_login = value
End Set
End Property
Private _login As Login = New Login()
End Class
Public Class Envelope
Public Property Body() As Body
Get
Return _body
End Get
Set(ByVal value As Body)
_body = value
End Set
End Property
Private _body As Body = New Body()
End Class
然后,创建一个信封对象,填充它,然后序列化它:
Then, create an envelope object, populate it, and then serialize it:
Dim envelope As New Envelope()
envelope.Body.Login.USERNAME = "username"
envelope.Body.Login.PASSWORD = "Sm@rt123"
Dim stream As MemoryStream = New MemoryStream()
Dim textWriter As XmlTextWriter = New XmlTextWriter(stream, New System.Text.UTF8Encoding(False))
Dim serializer As XmlSerializer = New XmlSerializer(GetType(Envelope))
Dim namespaces As XmlSerializerNamespaces = New XmlSerializerNamespaces()
namespaces.Add("", "")
serializer.Serialize(textWriter, envelope, namespaces)
Dim doc As XmlDocument = New XmlDocument()
doc.LoadXml(Encoding.UTF8.GetString(stream.ToArray()))
Dim xmlText As String = doc.SelectSingleNode("Envelope").OuterXml
这篇关于需要一种动态生成 XML 的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!