1

我有一种情况,我需要在我的 C# 代码中动态生成以下 XML。例如,XML 文本将是

<Envelope>
  <Body>
    <Login>
      <USERNAME>username</USERNAME>
      <PASSWORD>Sm@rt123</PASSWORD>
    </Login>
  </Body>
</Envelope>

要求是将上述 XML 格式作为字符串发送到 API 调用,它会以 XML 格式的字符串形式获得一些响应。

我的问题是上面的示例是针对 Login Api 调用的,对于所有 api 调用,元素 Envelope 和 Body 都是相同的,并且基于 api 调用,其他部分会像 Login api 一样发生变化,我需要提到一个 xml 元素使用其属性用户名和密码登录。

到目前为止,我一直在对上面的字符串进行硬编码并尝试测试功能是否正常工作,但现在我需要自动化为各个不同的 api 调用生成这些标签的过程。我需要知道如何做到这一点以及最好的方法是什么。

4

4 回答 4

4

像这样流利的东西...

internal class Program
{
    private static void Main(string[] args)
    {
        new API()
            .Begin()
            .Login("username", "password")
            .Send("someuri");
        Console.ReadLine();
    }
}

public class API
{
    public static readonly XNamespace XMLNS = "urn:hello:world";
    public static readonly XName XN_ENVELOPE = XMLNS + "Envelope";
    public static readonly XName XN_BODY = XMLNS + "Body";

    public XDocument Begin()
    {
        // this just creates the wrapper
        return new XDocument(new XDeclaration("1.0", Encoding.UTF8.EncodingName, "yes")
                                , new XElement(XN_ENVELOPE
                                    , new XElement(XN_BODY)));
    }
}

public static class APIExtensions
{
    public static void Send(this XDocument request, string uri)
    {
        if (request.Root.Name != API.XN_ENVELOPE)
            throw new Exception("This is not a request");

        // do something here like write to an http stream or something
        var xml = request.ToString();
        Console.WriteLine(xml);
    }
}

public static class APILoginExtensions
{
    public static readonly XName XN_LOGIN = API.XMLNS + "Login";
    public static readonly XName XN_USERNAME = API.XMLNS + "USERNAME";
    public static readonly XName XN_PASSWORD = API.XMLNS + "PASSWORD";

    public static XDocument Login(this XDocument request, string username, string password)
    {
        if (request.Root.Name != API.XN_ENVELOPE)
            throw new Exception("This is not a request");

        // you can have some fancy logic here
        var un = new XElement(XN_USERNAME, username);
        var pw = new XElement(XN_PASSWORD, password);
        var li = new XElement(XN_LOGIN, un, pw);
        request.Root.Element(API.XN_BODY).Add(li);
        return request;
    }
}
于 2012-05-22T16:04:39.403 回答
2
/// <summary>
///   Create an xml string in the expected format for the login API call.
/// </summary>
/// <param name="user">The user name to login with.</param>
/// <param name="password">The password to login with.</param>
/// <returns>
///   Returns the string of an xml document with the expected schema, 
///   to use with the login API.
/// </returns>
private static string GenerateXmlForLogin(string user, string password)
{
    return
        new XElement("Envelope",
            new XElement("Body",
                new XElement("Login",
                    new XElement("USERNAME", user),
                    new XElement("PASSWORD", password)))).ToString();
}
于 2012-05-22T15:58:14.500 回答
1

如果您在 wpf 中编写 c# 代码,此代码将帮助您很好地动态生成 xml 文件。

using System.Xml;


public Window1()
    {
        this.InitializeComponent();

        XmlDocument myxml = new XmlDocument();

        XmlElement envelope_tag = myxml.CreateElement("Envelope");

        XmlElement body_tag = myxml.CreateElement("Body");
        envelope_tag.AppendChild(body_tag);

        XmlElement Login_tag=myxml.CreateElement("Login");
        body_tag.AppendChild(Login_tag);

        XmlElement username = myxml.CreateElement("USERNAME");
        username.InnerText = "username";
        Login_tag.AppendChild(username);

        XmlElement password = myxml.CreateElement("PASSWORD");
        password.InnerText = "rt123";
        Login_tag.AppendChild(password);

        myxml.AppendChild(envelope_tag);
        myxml.Save(@"D:\Myxml.xml");   //you can save this file wherever you want to store. it may c: or D: and etc...      

    }

输出将是这样的

我的 XML

于 2012-06-09T05:06:06.207 回答
0

我将建议将序列化作为一种​​输出到 XML 的简单方法。这是一个简单的例子:

首先创建类

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

然后,创建一个信封对象,填充它,然后对其进行序列化:

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
于 2012-05-22T16:13:19.083 回答