简体   繁体   中英

Using .Net how do I deserialize the following xml?

I have the following xml (see below) that I want to de-serialize to the class Rule. I have not found the magical combination of xml attributes that allows me to store as text the xml content from the Parameters node in my xml input. I need an object of type Rule having the property Name = "Rule1" and property Parameters = "<User>Tommy</User><Database>local</Database>"

Thanks in advance.

<Rule>
  <Name>Rule1</Name>
  <Parameters>
    <User>Tommy</User>
    <Database>local</Database>
  </Parameters>
</Rule>

class Rule
{
  [XmlElement("Name")]
  public string Name { get; set; }
  [XmlElement("Parameters")]
  [XmlText(typeof(string))]
  public string Parameters { get; set; }
}

EDIT: I don't think I have been clear enough. I need to have the entire node named Parameters serialized to a string not to a custom class. As an example if an xml document was processed containing this

  <Parameters>
    <X>xxxx</X>
    <Y>yyyy</Y>
  </Parameters>

I need it deserialized to the string "<X>xxxx<Y>yyyy" If a different xml document contained this

  <Parameters>
    <A>aaaa</A>
    <B>bbbb</B>
  </Parameters>

I need it deserialized to the string "<A>aaaa<B>bbbb"

Simple enough?

XElement xDoc = XElement.Parse(xml); //or XElement.Load(...)
Rule rule = new Rule()
{
    Name = (string)xDoc.Element("Name"),
    Parameters = String.Join("",xDoc.Element("Parameters").Elements())
};

--

class Rule
{
    public string Name { get; set; }
    public string Parameters { get; set; }
}

Please consider using the OOP way like luksan suggested.

Otherwise, I would make up two placeholder classes for XmlSerializer support and then transform the objects into string maybe like

class Rule
{     
  public string Name { get; set; }    
  public string Parameters { get; set; }
}

class XmlRule
{
  [XmlElement("Name")]
  public string Name { get; set; }
  [XmlElement("Parameters")]
  public Parameters Parameters { get; set; }
}

class XmlParameters
{
   [XmlElement("User")]
   public string User { get; set; }
   [XmlElement("Database")]
   public string Database { get; set; }
}

public Rule CreateRule(string xml)
{
    XmlRule xmlRule = Deserialize(xml); // deserialize as you would do usually

    Rule result = new Rule
    {
        Name = xmlRule.Name,
        Parameters = CreateParametersXml(xmlRule.Parameters)
    };

    return result;
}

private string CreateParametersXml(XmlParameters parameters)
{
    return string.Format("<User>{0}</User><Database>{1}</Database>",
                         parameters.User,
                         parameters.Database);
}

Maybe not the best solution since the "<User>{0}</User><Database>{1}</Database>" stuff is hardcoded, what isn't that nice. But since I think the whole idea of having a non OOP model will cause trouble this seems the most simple solution for me.

Try this method:

public static string DeserializeToString(object obj)
        {
            var serializer = new XmlSerializer(obj.GetType());
            var ns = new XmlSerializerNamespaces();
            ns.Add("", "");
            var ms = new MemoryStream();
            var settings = new XmlWriterSettings { OmitXmlDeclaration = true, Encoding = new UnicodeEncoding(false, false) };
            var writer = XmlWriter.Create(ms, settings);
            serializer.Serialize(writer, obj, ns);

            return Encoding.Unicode.GetString(ms.ToArray());

        }

It will take an object and convert it to a string, omitting namespaces and XML declarations.

use like:

var rule = new Rule();
rule.Name = "name";
rule.Parameters = new Parameters();
rule.Parameters.User = "username";
rule.Parameters.Database = "database";

var stringResults = DeserializeToString(rule);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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