Consuming a REST XML web service

前端 未结 4 802
终归单人心
终归单人心 2020-12-13 16:11

I\'m trying to consume the following web service http://ipinfodb.com/ip_location_api.php this web service returns an xml response, the code below gets the XML response, but

4条回答
  •  温柔的废话
    2020-12-13 16:50

    You are assuming that first node will be root node but that's not correct. You will have XmlDeclaration node first and that may get followed by Whitespace nodes. So you should probably structure your code something like

    ...
    bool isRootRead = false;
    while (_xtr.Read())
    {
        if (_xtr.NodeType == XmlNodeType.Element)
        {
            if (!isRootRead)
            {
                if (_xter.Name == "Response")
                {
                    // root found
                    isRootRead = true;
                }
                // jump to next node if root node / ignore other nodes till root element is read
                continue;
            }
            _currentField = _xtr.Name;
            _xtr.Read();
            if (_xtr.NodeType == XmlNodeType.Text)
            {
                switch (_currentField)
                {
                    case "Status":
                        Console.WriteLine(_xtr.Value); //we print to console for testing purposes, normally assign it to a variable here!
                        break;
    ...
    

    But said all that, I would personally prefer to create response XSD (better if web service provides it) and generate classes out of it (using XSD.exe or Xsd2Code) for serialize/deserialise it.

提交回复
热议问题