简体   繁体   English

如何从ssms表创建带有嵌套xml的webapi?

[英]How can I create a webapi with nested xml from ssms table?

I have made a web api with C# and an ssms table. 我用C#和ssms表制作了一个Web api。 The result is an xml with only elements. 结果是仅包含元素的xml。

//This is only an example


 <?xml version="1.0" encoding="UTF-8"?>
    <note>
      <to>Tove</to>
      <from>Jani</from>
      <heading>Reminder</heading>
      <body>Don't forget me this weekend!</body>
    </note>

How can I format my xml as nested like this and add an optional different header from ssms table element??: 我如何格式化我的xml像这样嵌套,并从ssms表元素添加一个可选的不同标头?

<?xml version="1.0" encoding="UTF-8"?>
    <note>
      <to>Tove</to>
       <example>
        <from>Jani
         <heading>Reminder</heading>
        </from>
        <body>Don't forget me this weekend!</body>
      </example>
    </note>

Use xml linq : 使用xml linq:

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

namespace ConsoleApplication78
{
    class Program
    {

        static void Main(string[] args)
        {

            string xml = 
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                "<note>" +
                    "<to>Tove</to>" +
                    "<from>Jani</from>" +
                    "<heading>Reminder</heading>" +
                    "<body>Don't forget me this weekend!</body>" +
                "</note>";

            XDocument doc = XDocument.Parse(xml);

            XElement from = doc.Descendants("from").FirstOrDefault();
            XElement heading = doc.Descendants("heading").FirstOrDefault();
            XElement body = doc.Descendants("body").FirstOrDefault();

            from.Add(heading);

            XElement example = new XElement("example", new object[] {from,body});
            heading.Remove();
            body.Remove();
            from.ReplaceWith(example);


        }
    }
}

If you are creating from scratch 如果您是从头开始创建的

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

namespace ConsoleApplication78
{
    class Program
    {

        static void Main(string[] args)
        {

            string ident = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><note></note>";

            XDocument doc = XDocument.Parse(ident);
            XElement note = doc.Root;

            note.Add(new XElement("to", "Tove"),
                new XElement("example", new object[] {
                    new XElement("from", new object[] {
                        "Jani", new XElement("heading", "Reminder")
                    }),
                    new XElement("body","Don't forget me this weekend!")
                })
            );

        }
    }
}

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

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