Parse error not well formed ошибка

I am creating a sitemap XML from my database it’s about videos sitemap. In XML, I am fetching the video title as title and description as description, but there are some titles and descriptions written in Thai, Portuguese, German, and other languages. While generating the XML through PHP I am facing a problem that says:

«XML Parsing Error: not well-formed».

Generation of the XML stops after encountering this error.

XML Parsing Error: not well-formed
Location: http://localhost/mydesk/sitemap.php
Line Number 24489, Column 69:

I observed it contained invalid characters like listed below, and I have replaced all types of these characters, but I realized there are other characters being used in other languages.

Ð ž ´ Ø ¸ à ½ Ð ‰ ˆ Ù ° § ¼ ¡ ‹ ± …  ³ è ¾ Ñ € ¦ ƒ Ñ ‡ ª Ñ Ï ¿ ¬ µ š † Ð ½ ¹ Œ ² Ð ¼ Î ¶ € Ð µ ] : å < * © > % â © # » ‘ ä æ ï ã Š ç › Š º Ž ¥ œ • ¤ ç ã ® ˜ ¢ ¨ ¯ £

Is there any way to handle this issue that supports all languages?

The «XML Parsing Error: not well-formed» error message is encountered when an XML document is being parsed and the parser encounters an invalid XML syntax or structure that it cannot parse. This error message usually indicates that the XML document is not well-formed and therefore cannot be parsed by the parser. The error message can occur when the XML document is being loaded into an application, when it is being processed by an XML processor or when it is being transmitted over a network.

Method 1: Validate the XML Document

To fix the «XML Parsing Error: not well-formed» error, you can validate the XML document to ensure that it conforms to the XML standard. Here’s how you can do it in code:

  1. Load the XML document into a DOM parser:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xmlString)));
  1. Enable validation on the parser:
factory.setValidating(true);
builder.setErrorHandler(new DefaultHandler());
  1. Create a schema object:
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(new File(schemaFile));
  1. Validate the XML document against the schema:
Validator validator = schema.newValidator();
validator.validate(new DOMSource(document));

If the XML document is not well-formed, the validate() method will throw a SAXException with a detailed error message.

Here’s the complete code:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new DefaultHandler());

Document document = builder.parse(new InputSource(new StringReader(xmlString)));

SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(new File(schemaFile));

Validator validator = schema.newValidator();
validator.validate(new DOMSource(document));

This code will validate the XML document against the specified schema and throw an error if it is not well-formed.

Method 2: Check for Missing or Mismatched XML Elements

To fix the «XML Parsing Error: not well-formed» error, you can use the «Check for Missing or Mismatched XML Elements» method. This method involves checking for any missing or mismatched XML elements in your code.

To do this, you can use an XML validator tool such as XMLLint or an online validator like W3C Markup Validation Service. These tools will help you identify any missing or mismatched XML elements in your code.

Here’s an example of how to use XMLLint to validate your XML code:

xmllint --noout your_xml_file.xml

This command will check your XML file for any syntax errors and report back any issues it finds.

You can also use an XML editor like Visual Studio Code or Notepad++ to help you identify any missing or mismatched XML elements. These editors will highlight any syntax errors in your code and provide suggestions for fixing them.

Here’s an example of how to use Visual Studio Code to validate your XML code:

  1. Open your XML file in Visual Studio Code.
  2. Install the XML Tools extension if you haven’t already.
  3. Press Ctrl + Shift + P to open the Command Palette.
  4. Type «XML Validate» and select «XML Tools: Validate».
  5. Visual Studio Code will highlight any syntax errors in your code and provide suggestions for fixing them.

In conclusion, by using an XML validator tool or an XML editor, you can easily check for any missing or mismatched XML elements in your code and fix the «XML Parsing Error: not well-formed» error.

Method 3: Check for Special Characters in XML Element Names

One of the common causes of the «XML Parsing Error: not well-formed» error is having special characters in XML element names. To fix this, you can check for special characters in the element names and replace them with valid characters. Here’s how to do it in Python:

import re

pattern = re.compile(r'[^w]')

xml_string = '<root><first-name>John</first-name><last-name>Doe</last-name></root>'

clean_xml_string = pattern.sub('_', xml_string)

print(clean_xml_string)

In this example, we use the re module to define a regular expression pattern that matches any character that is not a word character (i.e., a letter, digit, or underscore). We then use the sub method of the pattern object to replace any matches with underscores. Finally, we output the cleaned XML string.

Note that this is just one way to fix the «XML Parsing Error: not well-formed» error. There may be other causes of the error that require different solutions.

Method 4: Check for Encoding Issues

When dealing with XML parsing errors, one common issue is encoding problems. The XML file may have been saved with an incorrect encoding, or there may be characters in the file that are not supported by the chosen encoding.

To check for encoding issues, you can use a tool like xmllint in the command line. Here are the steps to fix the XML parsing error with check for encoding issues:

  1. Open the command line and navigate to the directory where the XML file is located.

  2. Run the following command to check for encoding issues:

    xmllint --noout --encoding utf-8 <xml_file>

    This command will check the XML file for encoding issues and output any errors to the console. If there are no errors, the command will not output anything.

  3. If the command outputs any errors, you can fix them by changing the encoding of the XML file. You can use a text editor like Notepad++ to change the encoding. Here are the steps:

    • Open the XML file in Notepad++.
    • Click on the «Encoding» menu and select «Encode in UTF-8».
    • Save the file.
  4. After changing the encoding, run the xmllint command again to verify that there are no more encoding issues.

That’s it! By checking for encoding issues and fixing them, you can resolve the XML parsing error: not well-formed issue.

Method 5: Debug using an XML Validator

To debug an XML Parsing Error using an XML Validator, follow the steps below:

  1. First, you need to download an XML Validator. There are many validators available online, such as XML ValidatorBuddy, XML Notepad, and more. For this example, we will be using XML ValidatorBuddy.

  2. Open the XML file that is causing the parsing error in XML ValidatorBuddy.

  3. Click on the «Validate» button to validate the XML file. If the XML file is not well-formed, the validator will display an error message.

  4. Click on the error message to highlight the error in the XML file.

  5. Fix the error in the XML file. Once you have fixed the error, validate the XML file again to ensure that it is well-formed.

Here is an example of how to use XML ValidatorBuddy to debug an XML Parsing Error:

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
  <book>
    <title>XML Parsing Error Example</title>
    <author>John Doe</author>
    <price>19.99</price>
  </book>
  <book>
    <title>XML Parsing Error Example 2</title>
    <author>Jane Doe</author>
    <price>29.99</price>
  </book>
  <book>
    <title>XML Parsing Error Example 3</title>
    <author>Bob Smith</author>
    <price>24.99</price>
  </book>
</catalog>

If there is an error in this XML file, XML ValidatorBuddy will display an error message with details about the error. You can then click on the error message to highlight the error in the XML file. Once you have fixed the error, validate the XML file again to ensure that it is well-formed.

That’s it! By using an XML Validator, you can easily debug XML Parsing Errors and fix any issues in your XML files.

Chrome7
замечал, что это не корректный способ, но в моем случае он отработал идеально.

Завтра тебе пришлют новый документ, в котором будет смесь из амперсандов и сущностей — и твой сегодняшний код сломает завтрашний документ, повредив сущности.

То есть ты написал костыль. Пока человек идёт на костылях по улице, это выглядит приемлемо и похоже на обычного человека без костылей, но если вдруг ему нужно будет успеть на автобус, двери которого вот-вот закроются, то он не только его не догонит, но ещё и упадёт прямо на улице, не удержав костыли при беге, и будет очень долго валяться. Что хаки, что костыли, — это всё вредные вещи, которые на первый взгляд выглядят прекрасно, но эта прекрасность обманчива и очень часто потом выходит таким боком, что даже изсправить ничего не возможно, остаётся только всю программу заново писать, либо отказаться от её применения к новым данным.

Chrome7
Подробнее о том, как это корректно сделать можно прочитать здесь:

Во-первых, у него слишком короткое регулярное выражение, так как сущностей в XML может быть больше.
https://www.w3.org/TR/xml-entity-names/

И символы юникода также могут кодироваться через числовой код (в 10-чной и/или 16-ричной системе) с помощью амперсанда.
https://en.wikipedia.org/wiki/XML

All permitted Unicode characters may be represented with a numeric character reference.

Во-вторых, даже если просто заменить кавычку с сущности &apos; на простую кавычку, его код не сможет это исправить, потому что расчитан только на неправильно выраженный амперсанд в xml-документе, и исправить свой код, чтобы он ещё и кавычку учитывал, он не сможет, так как у кавычки гораздо больше смежных случаев, чем у амперсанда.

А как же это исправить? Выше я написал, как: надо сделать простейший транслятор, который сначала идентифицирует именно тот амперсанд в контексте и/или именно ту кавычку в контексте и только после этого заменит их. При этом будет гарантировано, что он не заменяет не тот амперсанд или не ту кавычку. То есть нужно написать лексический анализатор на базе ДКА. В общем случае понадобится магазин, но для частного случая можно и без магазина обойтись. Вот из-за того, что этот парнишка не знает программирование глубже школьника, он и побирается по всяким сайтам и в конечном итоге приходит к полурабочему решению.

Отредактировано py.user.next (Апрель 8, 2019 23:29:25)

RRS feed

  • Remove From My Forums
  • Question

  • I have WinXP Pro SP2.

    I downloaded and installed Visual Web Developer 2005 Express Edition.

    I am going through the Walkthroughs to better understand ASP.NET.

    I got to the Walkthrough: Creating a Web Site with Membership and User Login (ms-help://MS.VSExpressCC.v80/MS.NETFramework.v20.en/dv_vwdcon/html/296c0be6-9ad5-4104-9a1b-a853986fa1a3.htm)

    I performed every step up to Testing Login flawlessly (and every other Walkthrough up to this point). When I press Ctrl+F5 to run the Website I get this error:

    XML Parsing Error: not well-formed
    Location: http://localhost/membership/Default.aspx
    Line Number 1, Column 2:<%@ Page Language=»VB» AutoEventWireup=»false» CodeFile=»Default.aspx.vb» Inherits=»_Default» %>
    -^

     I can’t find any additional information on the problem in the MS Knowledge Bases so I don’t know how to fix it. Suggestions?


Answers

  • What we see that somehow ASPX file is parsed by XML parser.

    ASPX is not an XML and so this error is expected from XML parser.

    I’d recommend you to go to http://forums.asp.net/ to find why this happens.

All replies

  • What we see that somehow ASPX file is parsed by XML parser.

    ASPX is not an XML and so this error is expected from XML parser.

    I’d recommend you to go to http://forums.asp.net/ to find why this happens.

  • .ASPX files can be XML and can be parsed using XML parser. Example:

    <%@ Page Language=»VB» %>
    <script language=»VB» runat=»server»>
        Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
            ‘Set response to XML
            Response.ContentType = «text/xml»
            Dim dt As New System.Data.DataTable
            Try
                ‘Set connection string
                Dim connStr As String = «Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password»
                ‘Set Select statement
                Dim sql As String = «SELECT * FROM caddb.dbo.GetVehicles()» ‘Selects from the table valued function GetVehicles
                ‘Create Data Adapter specifying the select statement and connection string
                Dim da As New System.Data.SqlClient.SqlDataAdapter(sql, connStr)
                ‘Fill the DataTable with data
                da.Fill(dt)
            Catch ex As Exception
                ‘If connection failed, write the error instead
                Response.Write(«<Vehicles><error>»)
                Response.Write(ex.ToString)
                Response.Write(«</error></Vehicles>»)
                Exit Sub
            End Try
            ‘Write the XML Version info not required but is sujested
            Response.Write(«<?xml version=’1.0′ encoding=’utf-8′  standalone=’yes’?>»)
            ‘Write the parent node begin
            Response.Write(«<Vehicles>»)
            For Each row As System.Data.DataRow In dt.Rows ‘Cycle through the rows of the data table
                writeRowXML(row) ‘Write the row to XML
            Next
            ‘Write the parent node end
            Response.Write(«</Vehicles>»)
           
        End Sub
        Sub writeRowXML(ByRef row As System.Data.DataRow)
            Response.Write(«<Vehicle>»)
            Response.Write(»    <lat>» + row.Item(«lat»).ToString + «</lat>»)
            Response.Write(»    <lng>» + row.Item(«lng»).ToString + «</lng>»)
            Response.Write(»    <speed>» + row.Item(«speed»).ToString + «</speed>»)
            Response.Write(»    <heading>» + row.Item(«heading»).ToString + «</heading>»)
            Response.Write(»    <time>» + row.Item(«time»).ToString + «</time>»)
            Response.Write(«</Vehicle>»)
        End Sub
    </script>

    The resulting file would be XML. It would look like this:

    <Vehicles>
    <Vehicle>
    <lat>35.3738301</lat>
    <lng>-97.1908954</lng>
    <speed>0</speed>
    <heading>0</heading>
    <time>12/2/2006 1:42:30 AM</time>
    </Vehicle>
    <Vehicle>
    <lat>35.3838409</lat>
    <lng>-97.1908963</lng>
    <speed>45</speed>
    <heading>180</heading>
    <time>12/2/2006 1:42:30 AM</time>
    </Vehicle>
    </Vehicles>
  • hi did you ever find a solution to this problem

  • Hi,

    .ASPX file itself is not an XML. When you run it, it can produce XML as its output (as in your example). What sergey is saying is, that for some reason instead of the result fo the execution of your ASPX file (which would be an XML) the ASPX file itself is being parsed by the parser. And that fails (as expected).

    This is probably caused by a misconfiguration of the webserver serving the ASPX files (must be set to execute those and not serve them as a content file).

    Thanks,

  • I figured of this would be a problem with IIS and went to

    Finally I got it fixed this is what I did.

    Start -> settings -> control panel -> Add Remove Programs
    Selected Add Widows components
    Unchecked Internet Information Server (IIS)
    and clicked on  next to uninstall it

    Once I was uninstalled i followed the same process. This timed checked iis insted of
    uncheck to re install iis

    Start -> settings -> control panel -> Add Remove Programs
    Selected Add Widows components
    Checked Internet Information Server (IIS)
    and clicked on  next

    Again registered .net with iis

    Read More.

    http://muruganad.com/ASP.NET/XML-Parsing-Error-not-well-formed.html

    Thanks!
      Murugan
    www.muruganad.com

    • Edited by

      Tuesday, September 8, 2009 9:52 PM

  • This Doesn’t help I still get the error in vs 2008 of

    XML Parsing Error: syntax error
    Location: file:///C:/Users/Matthew.Matthew-PC/Documents/Visual%20Studio%202008/Projects/Go%204%20Ward/special.aspx
    Line Number 1, Column 1:This is a marker file generated by the precompilation tool, and should not be deleted!
    ^

  • I recently encountered this issue and it was solved very easy for me. I encountered it to due to a VS2008 Web Deployment Project. I marked for it to create a virtual directory however under the virtual directory settings it did not have a version of ASP.NET selected. Changing this in IIS fixed this occurrence for me.

    InetMGR

    Right click virtual directory < Properties

    ASP.NET

    Change drop down as appropriate.

    • Proposed as answer by
      Chris Marisic
      Monday, September 21, 2009 5:34 PM
    • Edited by
      Chris Marisic
      Monday, September 21, 2009 5:35 PM
      spelling

  • This Doesn’t help I still get the error in vs 2008 of

    XML Parsing Error: syntax error
    Location: file:///C:/Users/Matthew.Matthew-PC/Documents/Visual%20Studio%202008/Projects/Go%204%20Ward/special.aspx
    Line Number 1, Column 1:This is a marker file generated by the precompilation tool, and should not be deleted!
    ^

    You are loading an .aspx file from the file system. Load it over HTTP from a web server where ASP.NET is installed then it will work. With Visual Studio you have a development server or you can use IIS.


    MVP XML
    My blog

  • Not sure if you figured out this problem yet but try the following solution.

    Click on Start ->Run and type in the following command if you are using .NET 2.0 framework:
    %Windir%Microsoft.NETFrameworkv2.0.50727aspnet_regiis -i

    Once done the .NET Framework will be reinstalled. Your problem had to do with the fact that you no doubt installed the IIS after installing the .NET Framework. If the .NET Framework is not registered with IIS then it will not parse it properly.

  • Thank you. Reinstalling .NET 2.0 solved the issue.


The website is using WordPress 4.7.3
when executing
wp = Client("http://www.mywebsite.com/xmlrpc.php","myusername", "mypassword")

I got an error:

File «C:/02-folks/python-auto-send/upload_articles.py», line 20, in post_article
wp = Client(«http://www.mywebsite.com/xmlrpc.php»,»myusername», «mypassword»)
File «C:UsersWendy SunAppDataLocalProgramsPythonPython35-32libsite-packageswordpress_xmlrpcbase.py», line 24, in init
self.supported_methods = self.server.mt.supportedMethods()
File «C:UsersWendy SunAppDataLocalProgramsPythonPython35-32libxmlrpcclient.py», line 1091, in call
return self.__send(self.__name, args)
File «C:UsersWendy SunAppDataLocalProgramsPythonPython35-32libxmlrpcclient.py», line 1431, in __request
verbose=self.__verbose
File «C:UsersWendy SunAppDataLocalProgramsPythonPython35-32libxmlrpcclient.py», line 1133, in request
return self.single_request(host, handler, request_body, verbose)
File «C:UsersWendy SunAppDataLocalProgramsPythonPython35-32libxmlrpcclient.py», line 1149, in single_request
return self.parse_response(resp)
File «C:UsersWendy SunAppDataLocalProgramsPythonPython35-32libxmlrpcclient.py», line 1321, in parse_response
return u.close()
File «C:UsersWendy SunAppDataLocalProgramsPythonPython35-32libxmlrpcclient.py», line 654, in close
raise Fault(**self._stack[0])
xmlrpc.client.Fault: <Fault -32700: ‘parse error. not well formed’>

Process finished with exit code 1

Понравилась статья? Поделить с друзьями:
  • Parking brake fault ошибки на ситроен с5
  • Parkbremse losen что означает ошибка
  • Park ошибка что значит бмв
  • Park brake on ошибка туарег
  • Paris is most beautiful than london исправить ошибку