Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8193153
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T04:23:20+00:00 2026-06-07T04:23:20+00:00

Consider the following C# code: using System.Xml.Linq; namespace TestXmlParse { class Program { static

  • 0

Consider the following C# code:

using System.Xml.Linq;

namespace TestXmlParse
{
    class Program
    {
        static void Main(string[] args)
        {
            var testxml = 
            @"<base>
                <elem1 number='1'>
                    <elem2>yyy</elem2>
                    <elem3>xxx   <yyy zzz aaa</elem3>
                </elem1>
            </base>";
            XDocument.Parse(testxml);
        }
    }
}

I get a System.Xml.XmlException on the parse, of course, complaining about elem3. The error message is this:

System.Xml.XmlException was unhandled
  Message='aaa' is an unexpected token. The expected token is '='. Line 4, position 59.
  Source=System.Xml
  LineNumber=4
  LinePosition=59

Obviously this is not the real Xml (we get the xml from a third party) and while the best answer would be for the third party to clean up their xml before they send it to us, is there any other way I might fix this xml before I hand it off to the parser? I’ve devised a hacky way to fix this; catch the exception and use that to tell me where I need to look for characters which should be escaped. I was hoping for something a bit more elegant and comprehensive.

Any suggestions are welcome.

If this is a dupe, please point me to the other questions; I’ll close this myself. I am more interested in an answer than any karma gain.

EDIT:

I guess I didn’t make my question as clear as I had hoped. I know the “<” in elem3 is incorrect; I’m trying to find an elegant way to detect (and correct) any badly formed xml of that sort before I attempt the parse. As I say, I get this xml from a third-party and I can’t control what they give me.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T04:23:23+00:00Added an answer on June 7, 2026 at 4:23 am

    I would recommend that you do not manipulate the data you receive. If it is invalid it’s your client’s problem.

    Editing the input so it is valid xml can cause serious problems, e.g. instead of throwing an error you may end up processing wrong data (because you tried your best to make the xml valid, but this may lead to different data).


    [EDIT]
    I still think it’s not a good idea, but sometimes you have to do what you have to do.

    Here is a very simple class that parses the input and replaces the invald opening tag. You could do this with a regex (which I am not good at) and this solution is not complete, e.g. depending on your requirements (or lets say the bad xml you get) you will have to adopt it (e.g. scan for complete xml elements instead of only the “<” and “>” brackets, put CDATA around the inner text of a node and so on).

    I just wanted to illustrate how you could do it, so please don’t complain if it is slow/has bugs (as I mentioned, I would not do it).

    class XmlCleaner
        {
    
            public void Clean(Stream sourceStream, Stream targetStream)
            {
                const char openingIndicator = '<';
                const char closingIndicator = '>';
                const int bufferSize = 1024;
                long length = sourceStream.Length;
                char[] buffer = new char[bufferSize];
                bool startTagFound = false;
                StringBuilder writeBuffer = new StringBuilder();
    
                using(var reader = new StreamReader(sourceStream))            
                {
                    var writer = new StreamWriter(targetStream);
    
                    try
                    {
                        while (reader.Read(buffer, 0, bufferSize) > 0)
                        {
                            foreach (var c in buffer)
                            {
                                if (c == openingIndicator)
                                {
                                    if (startTagFound)
                                    {
                                        // we have 2 following opening tags without a closing one                                
                                        // just replace the first one
                                        writeBuffer = writeBuffer.Replace("<", "&lt;");
    
                                        // append the new one
                                        writeBuffer.Append(c);
                                    }
                                    else
                                    {
                                        startTagFound = true;
                                        writeBuffer.Append(c);
                                    }
                                }
                                else if (c == closingIndicator)
                                {
                                    startTagFound = false;
                                    // write writebuffer...
                                    writeBuffer.Append(c);
                                    writer.Write(writeBuffer.ToString());
                                    writeBuffer.Clear();
                                }
                                else
                                {
                                    writeBuffer.Append(c);
                                }
                            }
                        }
                    }
                    finally
                    {
                        // unfortunately the streamwriter's dispose method closes the underlying stream, so e just flush it
                        writer.Flush();
                    }                
                }
            }
    

    To test it:

    var testxml =
                @"<base>
                    <elem1 number='1'>
                        <elem2>yyy</elem2>
                        <elem3>xxx   <yyy zzz aaa</elem3>
                    </elem1>
                </base>";
    
                string result;
    
                using (var source = new MemoryStream(Encoding.ASCII.GetBytes(testxml)))
                using(var target = new MemoryStream()) {
    
                    XmlCleaner cleaner = new XmlCleaner();
                    cleaner.Clean(source, target);
    
                    target.Position = 0;
                    using (var reader = new StreamReader(target))
                    {
                        result = reader.ReadToEnd();
                    }
                }
    
                XDocument.Parse(result);
    
                var expectedResult = 
                    @"<base>
                    <elem1 number='1'>
                        <elem2>yyy</elem2>
                        <elem3>xxx   &lt;yyy zzz aaa</elem3>
                    </elem1>
                </base>";
                Debug.Assert(result == expectedResult);
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Consider the following code: using System; namespace ConsoleApplication2 { class Program { static void
Consider the following code: namespace DisposeTest { using System; class Program { static void
Consider the following code: using System; using System.Runtime.InteropServices; namespace Demo { class Program {
Consider the following code: namespace ConsoleApplication { using NamespaceOne; using NamespaceTwo; class Program {
Consider the following code: #include <iostream> using namespace std; int main() { int x,
Consider the following code: public class ReadingTest { public void readAndPrint(String usingEncoding) throws Exception
Consider the following code snippet: #include <vector> using namespace std; void sub(vector<int>& vec) {
Consider the following code: #include <iostream> #include <memory> #include <vector> using namespace std; struct
Consider the following code: [Serializable] public class Human { public string Name { get;
Consider the following code (written with Visual Studio 2010 and .NET 4.0) using System;

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.