没有subitem的xml序列化

时间:2016-06-27 19:36:45

标签: xml xml-serialization

如何离开此处

<no1SearchTerms>
  <no1SearchTerm language="EN" value="bodywash" /> 
  <no1SearchTerm language="EN" value="body soap" /> 
  <no1SearchTerm language="EN" value="body wash" /> 
  <no1SearchTerm language="EN" value="body wash men" /> 
  <no1SearchTerm language="EN" value="body wash for women" /> 
</no1SearchTerms> 

到这里,使用xml序列化

<no1SearchTerms>
  <language="EN" value="bodywash" /> 
  <language="EN" value="body soap" /> 
  <language="EN" value="body wash" /> 
  <language="EN" value="body wash men" /> 
  <language="EN" value="body wash for women" /> 
</no1SearchTerms>  

数据序列化的类

public class  no1SearchTerm
               {    [XmlAttribute]
                    public string language { get; set; }
                    [XmlAttribute]
                    public string value { get; set; }
                }


        [XmlRoot("Items")]
           public class myData
           {

               public class _data
               {
                   [XmlArray("no1SearchTerms")]
                   public List<no1SearchTerm> no1SearchTerm;
               }
    }

2 个答案:

答案 0 :(得分:0)

无需序列化。使用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 =
                "<no1SearchTerms>" +
                  "<no1SearchTerm language=\"EN\" value=\"bodywash\" />" +
                  "<no1SearchTerm language=\"EN\" value=\"body soap\" />" +
                  "<no1SearchTerm language=\"EN\" value=\"body wash\" />" +
                  "<no1SearchTerm language=\"EN\" value=\"body wash men\" />" +
                  "<no1SearchTerm language=\"EN\" value=\"body wash for women\" />" +
                "</no1SearchTerms>";

            XElement terms = XElement.Parse(xml);
            List<XElement> no1SearchTerms = terms.Descendants("no1SearchTerm").ToList();
            for (int index = no1SearchTerms.Count - 1; index >= 0; index-- )
            {
                no1SearchTerms[index].ReplaceWith(new XElement("language", no1SearchTerms[index].Attribute("value")));
            }

        }
    }
}

答案 1 :(得分:0)

后端人员只使用这种格式:

<no1SearchTerm>
      <value language="EN">bodywash</value>
      <value language="EN"> body soap</value>
      <value language="EN"> body wash</value>
      <value language="EN"> body wash men</value>
</no1SearchTerm>

这是通过对类属性的调整来完成的

[Serializable]
           [XmlRoot("no1SearchTerm")]
           public class _no1SearchTerm
           {
               [XmlAttribute]
               public string language { get; set; }
               [XmlText]
               public string value { get; set; }
           }

[XmlArray("no1SearchTerm")]
           [XmlArrayItem("value")]
           public List<_no1SearchTerm> no1SearchTerm;