Domanda

I have a program which uses OpenCV to read xml files in a C++ program. I want to change my xml files using a C# program. When I use Save function of XDocument class, I get the following error: "Invalid character in the stream"

When I checked the stream, I contained the following string:

<?xml version="1.0" encoding="utf-8"?>

I thought that the starting characters are because of utf-8, so I used this method to save my xml in ASCII format. Encoding of my xml file changed to ascii, but encoding="us-ascii" was written in the xml file. My problem is that OpenCv checks if encoding is ASCII and since it is written us-ascii, It throws exception. Is there any solution to write ASCII for encoding attribute in the xml saved by XDocument?

È stato utile?

Soluzione

You could achieve that by creating a new Encoding class and overriding WebName like this:

    public class NonUsAsciiEncoding : ASCIIEncoding
    {
        public override string WebName
        {
            get
            {
                return "ascii";
            }
        }
    }

    private void CreateXml()
    {       
        XmlTextWriter xmlwriter = new XmlTextWriter("c:\\test.xml", new NonUsAsciiEncoding());        

        XDocument xdoc = new XDocument(
          new XElement("Test")
        );

        xdoc.Save(xmlwriter);
        xmlwriter.Close();
    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top