简体   繁体   English

How to programatically build an xml with soap in c# with xmlns:soap12, xmlns:xsd and xmlns:xsi in c#?

[英]How to programatically build an xml with soap in c# with xmlns:soap12, xmlns:xsd and xmlns:xsi in c#?

I need to programatically created a xml that looks like so:我需要以编程方式创建一个看起来像这样的 xml:

<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <Profile xmlns="http://google.com">
      <number>123</number>
      <name>bob</name>
    </Profile>
  </soap12:Body>
</soap12:Envelope>

Currently it looks like this:目前它看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <Profile xmlns="http://google.com">
      <number>123</number>
      <name>bob</name>
    </Profile>
  </soap12:Body>
</soap12:Envelope>

The code I have so far is:我到目前为止的代码是:

            using (XmlWriter writer = XmlWriter.Create(@"C:\Users\Default\Desktop\books.xml"))
            {
                writer.WriteStartElement("soap12", "Envelope", "http://www.w3.org/2001/XMLSchema-instance");
                writer.WriteStartElement("soap12", "Body", null);
                writer.WriteStartElement("Profile", "http://google.com");

                writer.WriteElementString("number", "123");
                writer.WriteElementString("name", "bob");

            }

Can someone please help me with this one?有人可以帮我解决这个问题吗?

Thank you!谢谢!

Use xml linq:使用 xml linq:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                          "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" +
                             " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"" +
                             " xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">" +
                          "</soap12:Envelope>";

            XDocument doc = XDocument.Parse(xml);
            XElement envelope = doc.Root;
            XNamespace soap12Ns = envelope.GetNamespaceOfPrefix("soap12");


            XElement body = new XElement(soap12Ns + "Body");
            envelope.Add(body);

            XNamespace ns = "http/://google.com";
            XElement profile = new XElement(ns + "Profile");
            body.Add(profile);

            profile.Add(new object[] {
                new XElement(ns + "number", 123),
                new XElement(ns + "name", "bob")
            });



        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM