XML parsing question

Hello

I'm trying to parse the following XML code which I get from a webservice:

"<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse><params><param><value><struct><member><name>result</name><value><boolean>0</boolean></value></member><member><name>result_text</name><value><base64>SomeBase64Code</base64></value></member></struct></value></param></params></methodResponse>"

I've tryed to use XmlReader, but it doesnt parse it (but no error message).

Then I've tried this code:

  StringReader aaa = new StringReader(responseString);
  var xmlResults = XDocument.Load(aaa);

It does load the "Declaration", but it doesnt parse the XML itself. So FirstNode and LastNode is just:

<params>
  <param>
    <value>
      <struct>
        <member>
          <name>result</name>
          <value>
            <boolean>0</boolean>
          </value>
        </member>
        <member>
          <name>result_text</name>
          <value>

            <base64>SomeBase64Code</base64>
          </value>
        </member>
      </struct>
    </value>
  </param>
</params>

Whats wrong? is the XML in a wrong Format?

Thanks a lot

James
RuttensoftAsked:
Who is Participating?
 
skullnobrainsCommented:
your xml contains a single "methodResponse" node.
this node happens to be both the first and the last

if you want the result text, you need something like
XmlResults.Elements("result_text")

---

as a side note, this looks a lot like soap, so using a dedicated soap extension should probably be considered

happy coding
0
 
RuttensoftAuthor Commented:
Hi and thanks for your answer!

So would it be possible to directly parse it in a Class with bool result and string result_text?
I've used this before using JSON and a JSON Parser/deserializer...

Thanks
0
 
aplusexpertCommented:
I don't know what do you actually want???

but I think there is no need to take stream reader becausexml string directly load to xmldocument. So comment below line

// StringReader aaa = new StringReader(responseString);

and try your code.

and if its not working store xml string to dataset and then get value from that dataset.

StringReader stream = null;
XmlTextReader reader = null;

DataSet ds = new DataSet();
stream = new StringReader(Session["XMLDoc"].ToString());
reader = new XmlTextReader(stream); // Load the XmlTextReader from the stream
ds.ReadXml(reader);

Open in new window


Thanks.
0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
skullnobrainsCommented:
use elements("result") and elements("result_text")

you cannot parse an XML to a set of structures in C because the structure would depend on the XML file itself, so the compiler would not know of the structure at compile time.

since your XML is normalised, you obviously can create a C++ class with the 2 interesting properties, and a constructor that will instanciate the object from the XML. possibly build the class as an extension of XMLDocument

but again, i think you will just be implementing yet another SOAP parser

if you really want it quick and dirty, it is arguably simpler to use a regexp, or plain old string functions to perform the task. something like this :

--> strpos of "<name>result</name><value><boolean>1</boolean></value>"
--> if found, return ok
--> if not found use a regexp to retrieve the error string and raise an error containing the retrieved text
0
 
käµfm³d 👽Commented:
you cannot parse an XML to a set of structures in C because the structure would depend on the XML file itself, so the compiler would not know of the structure at compile time.
I won't hazard to speak about C, but as the topic of this question is in C#...  you can certainly deserialize an XML blurb to a class (or struct) assuming the XML in question does match the structure of the class. You can use either the XmlSerializer class or the DataContractSerializer class. I wrote a couple of articles dealing with XmlSerializer:


DataContractSerializer is something new for me, so I don't have any articles dealing with it, but as I understand it the process is very similar (if not identical) to what I describe for XmlSerializer--it's just using a different class.
0
 
skullnobrainsCommented:
true, thanks for correcting, and the nice article as well

but i do not think that really is what the author needs, which should rather be a quick shorthand to retrieve the result and text, and basically understanding that nodes are nestable and a nodes "content" is actually the textual representation of its child nodes
0
 
käµfm³d 👽Commented:
I'm basing my answer on this comment:

So would it be possible to directly parse it in a Class...

...which I inferred to mean "to a Class." It that is truly what he wants to do, then I stand by my previous comment. If instead he simply wants to extract a piece of text out of the whole of the XML, then I could agree that simple string searching could suffice. However, I maintain that it's just as easy to load the XML into an appropriate data structure (XElement for instance) and use methods to navigate the XML. Unless you are running a heavy load, the performance gain you would see using string parsing would be unnoticeable.
0
 
skullnobrainsCommented:
@kaufmed, offtopic

i wasn't flaming, kaufmed

my thanks were genuine, and the concern about parsing SOAP without using the existing APIs as well

and agreed, the performance gain is meaningless since whatever parsing method will definitely be much faster than asking the server over the network
0
 
käµfm³d 👽Commented:
i wasn't flaming, kaufmed
I didn't take it as such; just defending why I would take the position I stated versus what you offered  = )
0
 
RuttensoftAuthor Commented:
Hi all

Thanks a lot for your answers.
Actually the given XML text is only one sample, I'm getting a lot of different XML Responses which I want to parse.

Until now I'm doing it manually with Regex.Split(...). But it seems that Windows 8 Metro is SLOW on doing Regex! THat's why I was interested in parsing it directly using a Serializer. But as I found out, XMLSerializer is NOT part of Windows 8 Metro Framework! Argh...

So I have to optimize this parsing somehow else.

I'm using this until now:

        private object XMLParsing(string str, string what, string type)
        {
            string result = Regex.Split(str, string.Format("<name>{0}</name><value><{1}>", what, type))[1];
            result = Regex.Split(result, string.Format("</{0}>", type))[0];
            switch(type)
            {
                case "boolean":
                    return Convert.ToBoolean(result);
                case "base64":
                    byte[] b = Convert.FromBase64String(result);
                    return Encoding.UTF8.GetString(b,0,b.Length);
                default:
                    return result;
            }
        }

Can I use Regex better for this? Until now I am using 2x Regex queries...

THanks
0
 
skullnobrainsCommented:
i do not know which regexpr engine you are using but something like this should do the trick

<name>([^<]*)</name>[[:space:]]*<value><([^>]*)>([^<]*)</[^>]*></value>

first parenthesis should capture the name of the answer (response or response text)
second should capture the data type
third should capture the value

ask for all the matches (you'll get one for the response and another for the response text) or possibly built a bigger regexp that will directly capture all 6 interesting values at once

but then this will only work providing the server always answers in the exact same way, always with either boolean or base 64 formats, always with a single responsetext item, and always sends the name befor the value which is not required in any RFC although all the SOAP servers probably do...

i do not know a thing about  Windows 8 Metro but i'm pretty sure there is an existing SOAPclient that will do all the data parsing and conversion you may need, and throw a decent error if the parsing fails for some reason

happy coding
0
 
käµfm³d 👽Commented:
But as I found out, XMLSerializer is NOT part of Windows 8 Metro Framework!
How did you come by this information?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.