Parsing xml string to an xml document fails if the string begins with <?xml… ?> section

前端 未结 5 949
闹比i
闹比i 2021-01-01 11:41

I have an XML file begining like this:




        
5条回答
  •  灰色年华
    2021-01-01 12:11

    If you only have bytes you could either load the bytes into a stream:

    XmlDocument oXML;
    
    using (MemoryStream oStream = new MemoryStream(oBytes))
    {
      oXML = new XmlDocument();
      oXML.Load(oStream);
    }
    

    Or you could convert the bytes into a string (presuming that you know the encoding) before loading the XML:

    string sXml;
    XmlDocument oXml;
    
    sXml = Encoding.UTF8.GetString(oBytes);
    oXml = new XmlDocument();
    oXml.LoadXml(sXml);
    

    I've shown my example as .NET 2.0 compatible, if you're using .NET 3.5 you can use XDocument instead of XmlDocument.

    Load the bytes into a stream:

    XDocument oXML;
    
    using (MemoryStream oStream = new MemoryStream(oBytes))
    using (XmlTextReader oReader = new XmlTextReader(oStream))
    {
      oXML = XDocument.Load(oReader);
    }
    

    Convert the bytes into a string:

    string sXml;
    XDocument oXml;
    
    sXml = Encoding.UTF8.GetString(oBytes);
    oXml = XDocument.Parse(sXml);
    

提交回复
热议问题