Read a XML (from a string) and get some fields - Problems reading XML

前端 未结 5 1344
青春惊慌失措
青春惊慌失措 2020-12-04 12:09

I have this XML (stored in a C# string called myXML)




        
相关标签:
5条回答
  • 2020-12-04 12:20

    I used the System.Xml.Linq.XElement for the purpose. Just check code below for reading the value of first child node of the xml(not the root node).

            string textXml = "<xmlroot><firstchild>value of first child</firstchild>........</xmlroot>";
            XElement xmlroot = XElement.Parse(textXml);
            string firstNodeContent = ((System.Xml.Linq.XElement)(xmlroot.FirstNode)).Value;
    
    0 讨论(0)
  • 2020-12-04 12:30

    The other answers are several years old (and do not work for Windows Phone 8.1) so I figured I'd drop in another option. I used this to parse an RSS response for a Windows Phone app:

    XDocument xdoc = new XDocument();
    xdoc = XDocument.Parse(xml_string);
    
    0 讨论(0)
  • 2020-12-04 12:40

    You should use LoadXml method, not Load:

    xmlDoc.LoadXml(myXML); 
    

    Load method is trying to load xml from a file and LoadXml from a string. You could also use XPath:

    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.LoadXml(xml);
    
    string xpath = "myDataz/listS/sog";
    var nodes = xmlDoc.SelectNodes(xpath);
    
    foreach (XmlNode childrenNode in nodes)
    {
        HttpContext.Current.Response.Write(childrenNode.SelectSingleNode("//field1").Value);
    } 
    
    0 讨论(0)
  • 2020-12-04 12:40

    Or use the XmlSerializer class.

    XmlSerializer xs = new XmlSerializer(objectType);
    obj = xs.Deserialize(new StringReader(yourXmlString));
    
    0 讨论(0)
  • 2020-12-04 12:43

    Use Linq-XML,

    XDocument doc = XDocument.Load(file);
    
    var result = from ele in doc.Descendants("sog")
                  select new
                  {
                     field1 = (string)ele.Element("field1")
                  };
     foreach (var t in result)
      {
          HttpContext.Current.Response.Write(t.field1);
      }
    

    OR : Get the node list of <sog> tag.

     XmlDocument xmlDoc = new XmlDocument();
     xmlDoc.Load(myXML);
     XmlNodeList parentNode = xmlDoc.GetElementsByTagName("sog");
     foreach (XmlNode childrenNode in parentNode)
      {
        HttpContext.Current.Response.Write(childrenNode.SelectSingleNode("field1").InnerText);
       }
    
    0 讨论(0)
提交回复
热议问题