using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Xml;

namespace TEAMModelOS.SDK.Helper.Common.XmlHelper
{
    public class XmlAndJson
    {  /// <summary>
       /// 返回指定节点下信息的JSON格式字符串
       /// </summary>
       /// <param name="str">xml字符串</param>
       /// <param name="nodename">节点名称，应从根节点开始</param>
       /// <returns></returns>
        public static string XML2Json(string str, string nodename)
        {
            string result = null;
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.LoadXml(str);
            XmlNode node = xmldoc.SelectSingleNode(nodename);
            result = Newtonsoft.Json.JsonConvert.SerializeXmlNode(node);
            return result;
        }

        public static string Json2XML(string str)
        {
            string result = null;
            XmlDocument xml = Newtonsoft.Json.JsonConvert.DeserializeXmlNode(str);
            result = xml.OuterXml;
            return result;
        }
        public static string GetCustomItemSpecifics(string str)
        {
            DataTable dt = JsonConvert.DeserializeObject<DataTable>(str);

            List<Json2Xml.NameValueListType> nvl = new List<Json2Xml.NameValueListType>();

            foreach (DataRow dr in dt.Rows)
            {
                Json2Xml.NameValueListType nv = new Json2Xml.NameValueListType();

                string sName = dr["Name"].ToString();
                string sValue = dr["Value"].ToString();

                if (sName != string.Empty && sValue != string.Empty)
                {
                    nv.Name = sName;
                    nv.Value = new string[] { sValue };
                    nvl.Add(nv);
                }
            }

            if (nvl.Count == 0)
            {
                return string.Empty;
            }
            else
            {
                Json2Xml.CustomItemSpecifics t = new Json2Xml.CustomItemSpecifics();
                t.ItemSpecifics = nvl.ToArray();
                return Json2Xml.ObjectToText(t, typeof(Json2Xml.CustomItemSpecifics));
            }
        }
    }
}
