Skip wrapping elements when deserializing XML with C# / .NET -
i trying deserialize incoming xml data c#/.net 3.5 using class hierarchy starts class tagged xmlroot , contains classes , members required attributes. works far.
now have come across input data looks approximately this:
<?xml version="1.0" encoding="utf-8"?> <ns1:foo xmlns:ns1="http://some.name/space"> <ns1:bar> <payload interesting="true"> <stuff type="interesting"/> </payload> </ns1:bar> </ns1:foo> the outermost 2 elements - ns1:foo , ns1:bar - results of serialization process in remote system have no control over. exist in same constellation , of no interest whatsoever.
following current approach, write class foo references class bar in turn references class payload. however, since i'm not interested in foo , bar elements, there way skip them during deserialization , have deserializer return payload? if not: possible make class foopayload xmlroot(elementname = "foo", namespace = "http://some.name/space")attribute, somehow skip bar , payload levels foopayload class directly contains properties named interesting , stuff?
i modified xml correct errors. see interesting solution below.
using system; using system.collections.generic; using system.linq; using system.text; using system.xml; using system.xml.serialization; using system.io; using system.text.regularexpressions; namespace consoleapplication1 { class program { static void main(string[] args) { string input = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<ns1:foo xmlns:ns1=\"http://some.name/space\">" + "<ns1:bar>" + "<ns1:payload interesting=\"true\">" + "<ns1:stuff type=\"interesting\"/>" + "</ns1:payload>" + "</ns1:bar>" + "</ns1:foo>"; //remove prefix string pattern = "(</?)([^:]*:)"; regex expr = new regex(pattern); input = expr.replace(input, "$1"); xmlserializer xs = new xmlserializer(typeof(foo)); stringreader s_reader = new stringreader(input); xmltextreader reader = new xmltextreader(s_reader); foo foo = (foo)xs.deserialize(reader); foo.getstuff(); } } [xmlroot(elementname = "foo")] public class foo { [xmlelement("bar")] public bar bar { get; set; } private boolean interesting; private string type; public void getstuff() { interesting = bar.payload.interesting; type = bar.payload.stuff.type; } } [xmlroot("bar")] public class bar { [xmlelement("payload")] public payload payload { get; set; } } [xmlroot("payload")] public class payload { [xmlattribute("interesting")] public boolean interesting { get; set; } [xmlelement("stuff")] public stuff stuff { get; set; } } [xmlroot("stuff")] public class stuff { [xmlattribute("type")] public string type { get; set; } } }
Comments
Post a Comment