JamesNK/Newtonsoft.Json · error · JsonSerializationException

Unexpected XmlNodeType when serializing nodes:

Error message

Unexpected XmlNodeType when serializing nodes: 

What it means

Thrown by XmlNodeConverter.SerializeNode's default case when an IXmlNode's NodeType is not among the handled document/element/attribute/comment/CDATA/text/whitespace/processing-instruction/document-type/declaration types. Like error [16] but in the main node-serialization switch; the message is unterminated so the offending NodeType is not echoed.

Source

Thrown at Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs:1455

                    {
                        writer.WritePropertyName("@public");
                        writer.WriteValue(documentType.Public);
                    }
                    if (!StringUtils.IsNullOrEmpty(documentType.System))
                    {
                        writer.WritePropertyName("@system");
                        writer.WriteValue(documentType.System);
                    }
                    if (!StringUtils.IsNullOrEmpty(documentType.InternalSubset))
                    {
                        writer.WritePropertyName("@internalSubset");
                        writer.WriteValue(documentType.InternalSubset);
                    }

                    writer.WriteEndObject();
                    break;
                default:
                    throw new JsonSerializationException("Unexpected XmlNodeType when serializing nodes: " + node.NodeType);
            }
        }

        private static bool AllSameName(IXmlNode node)
        {
            foreach (IXmlNode childNode in node.ChildNodes)
            {
                if (childNode.LocalName != node.LocalName)
                {
                    return false;
                }
            }
            return true;
        }
#endregion

        #region Reading
        /// <summary>

View on GitHub (pinned to 4f73e74372)

Solutions

  1. Expand/normalize the XML before serialization so all nodes are of supported types (resolve entity references, drop notation declarations).
  2. Load XML with XmlReaderSettings configured to expand entities (DtdProcessing.Parse) so entity-reference nodes do not appear.
  3. If implementing a custom IXmlNode, ensure NodeType values are within the supported set.

Example fix

// before: entity references survive as unsupported nodes
var doc = new XmlDocument(); doc.Load(path); // keeps EntityReference nodes
JsonConvert.SerializeXmlNode(doc);

// after: expand entities during load
var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Parse };
using var reader = XmlReader.Create(path, settings);
var doc = new XmlDocument(); doc.Load(reader);
JsonConvert.SerializeXmlNode(doc);
Defensive patterns

Strategy: validation

Validate before calling

foreach (System.Xml.XmlNode node in doc.ChildNodes)
    AssertSerializableNodeType(node);

static void AssertSerializableNodeType(System.Xml.XmlNode n)
{
    if (n.NodeType == XmlNodeType.EntityReference || n.NodeType == XmlNodeType.Entity
        || n.NodeType == XmlNodeType.Notation || n.NodeType == XmlNodeType.EndElement
        || n.NodeType == XmlNodeType.None)
        throw new InvalidDataException($"Unsupported XmlNodeType: {n.NodeType}");
    foreach (System.Xml.XmlNode child in n.ChildNodes) AssertSerializableNodeType(child);
}

Type guard

static bool IsSerializableXmlNode(System.Xml.XmlNodeType t) =>
    t == XmlNodeType.Element || t == XmlNodeType.Attribute || t == XmlNodeType.Text
    || t == XmlNodeType.CDATA || t == XmlNodeType.Comment || t == XmlNodeType.Whitespace
    || t == XmlNodeType.SignificantWhitespace || t == XmlNodeType.ProcessingInstruction
    || t == XmlNodeType.Document || t == XmlNodeType.DocumentFragment
    || t == XmlNodeType.DocumentType || t == XmlNodeType.XmlDeclaration;

Try / catch

try { JsonConvert.SerializeXmlNode(doc); }
catch (JsonSerializationException ex) when (ex.Message.Contains("Unexpected XmlNodeType when serializing nodes"))
{
    throw new InvalidDataException("XML contains a node type the converter cannot serialize", ex);
}

Prevention

When it happens

Trigger: Serializing an XML document containing a node type the converter does not serialize (e.g. XmlNodeType.EntityReference, XmlEntityType, XmlNotationType, or a custom IXmlNode with an unsupported NodeType).

Common situations: XML with entity references or notation nodes not expanded during load. Custom IXmlNode wrappers returning novel node types. Cross-runtime XML DOM differences surfacing uncommon nodes.

Related errors


AI-assisted analysis of JamesNK/Newtonsoft.Json@4f73e74372 (2026-08-07). Data as JSON: /api/errors/34fd3455c83d1e7c. Report an issue: GitHub.