需要一种动态生成XML的方法

时间:2012-05-22 15:45:43

标签: c# xml

我遇到需要在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元素作为Login,其属性用户名和密码。

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

4 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分: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();
}

答案 2 :(得分: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...      

    }

输出将是这样的

MyXml

答案 3 :(得分: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