Can not read XML document containing ampersand symbol

后端 未结 1 1380
眼角桃花
眼角桃花 2021-01-19 09:31

I am writing a program that reads a XML file with Visual C#. I have a problem reading the Xml file, because it contains invalid XML symbols, for example \'&\'.

相关标签:
1条回答
  • 2021-01-19 10:15

    As @EBrown suggested, one possibility would be read the file content in a string variable and replace the & symbol with the correct representation for propert XML & and then parse the XML structure. A possible solution could look like this:

    var xmlContent = File.ReadAllText(@"nuevo.xml");
    XmlDocument doc;
    doc = new XmlDocument();
    doc.LoadXml(xmlContent.Replace("&", "&"));
    
    XmlNodeList Xpersonas = doc.GetElementsByTagName("personas");
    XmlNodeList Xlista = ((XmlElement)Xpersonas[0]).GetElementsByTagName("edad");
    
    foreach (XmlElement nodo in Xlista)
    {
        string edad = nodo.GetAttribute("edad");
        string nombre = nodo.InnerText;
        Console.WriteLine(nodo.InnerXml.Replace("&", "&"));
    }
    

    The output is:

    34 & 34 
    

    If it is ok to use LINQ2XML, then the solution is even shorter, and there is no need to write the reverse(second) replace, because LINQ2XML make this for you automatically:

    var xmlContent = File.ReadAllText(@"nuevo.xml");
    var xmlDocument = XDocument.Parse(xmlContent.Replace("&", "&"));
    var edad = xmlDocument.Root.Element("edad").Value;
    Console.WriteLine(edad);
    

    The output is the same as above.

    0 讨论(0)
提交回复
热议问题