{"record":{"id":"34fd3455c83d1e7c","repo":"JamesNK/Newtonsoft.Json","slug":"unexpected-xmlnodetype-when-serializing-nodes","errorCode":null,"errorMessage":"Unexpected XmlNodeType when serializing nodes: ","messagePattern":"Unexpected XmlNodeType when serializing nodes: ","errorType":"exception","errorClass":"JsonSerializationException","httpStatus":null,"severity":"error","filePath":"Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs","lineNumber":1455,"sourceCode":"                    {\n                        writer.WritePropertyName(\"@public\");\n                        writer.WriteValue(documentType.Public);\n                    }\n                    if (!StringUtils.IsNullOrEmpty(documentType.System))\n                    {\n                        writer.WritePropertyName(\"@system\");\n                        writer.WriteValue(documentType.System);\n                    }\n                    if (!StringUtils.IsNullOrEmpty(documentType.InternalSubset))\n                    {\n                        writer.WritePropertyName(\"@internalSubset\");\n                        writer.WriteValue(documentType.InternalSubset);\n                    }\n\n                    writer.WriteEndObject();\n                    break;\n                default:\n                    throw new JsonSerializationException(\"Unexpected XmlNodeType when serializing nodes: \" + node.NodeType);\n            }\n        }\n\n        private static bool AllSameName(IXmlNode node)\n        {\n            foreach (IXmlNode childNode in node.ChildNodes)\n            {\n                if (childNode.LocalName != node.LocalName)\n                {\n                    return false;\n                }\n            }\n            return true;\n        }\n#endregion\n\n        #region Reading\n        /// <summary>","sourceCodeStart":1437,"sourceCodeEnd":1473,"githubUrl":"https://github.com/JamesNK/Newtonsoft.Json/blob/4f73e74372445108d2c1bda37b36e6f5e43402e0/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs#L1437-L1473","documentation":"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.","triggerScenarios":"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).","commonSituations":"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.","solutions":["Expand/normalize the XML before serialization so all nodes are of supported types (resolve entity references, drop notation declarations).","Load XML with XmlReaderSettings configured to expand entities (DtdProcessing.Parse) so entity-reference nodes do not appear.","If implementing a custom IXmlNode, ensure NodeType values are within the supported set."],"exampleFix":"// before: entity references survive as unsupported nodes\nvar doc = new XmlDocument(); doc.Load(path); // keeps EntityReference nodes\nJsonConvert.SerializeXmlNode(doc);\n\n// after: expand entities during load\nvar settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Parse };\nusing var reader = XmlReader.Create(path, settings);\nvar doc = new XmlDocument(); doc.Load(reader);\nJsonConvert.SerializeXmlNode(doc);","handlingStrategy":"validation","validationCode":"foreach (System.Xml.XmlNode node in doc.ChildNodes)\n    AssertSerializableNodeType(node);\n\nstatic void AssertSerializableNodeType(System.Xml.XmlNode n)\n{\n    if (n.NodeType == XmlNodeType.EntityReference || n.NodeType == XmlNodeType.Entity\n        || n.NodeType == XmlNodeType.Notation || n.NodeType == XmlNodeType.EndElement\n        || n.NodeType == XmlNodeType.None)\n        throw new InvalidDataException($\"Unsupported XmlNodeType: {n.NodeType}\");\n    foreach (System.Xml.XmlNode child in n.ChildNodes) AssertSerializableNodeType(child);\n}","typeGuard":"static bool IsSerializableXmlNode(System.Xml.XmlNodeType t) =>\n    t == XmlNodeType.Element || t == XmlNodeType.Attribute || t == XmlNodeType.Text\n    || t == XmlNodeType.CDATA || t == XmlNodeType.Comment || t == XmlNodeType.Whitespace\n    || t == XmlNodeType.SignificantWhitespace || t == XmlNodeType.ProcessingInstruction\n    || t == XmlNodeType.Document || t == XmlNodeType.DocumentFragment\n    || t == XmlNodeType.DocumentType || t == XmlNodeType.XmlDeclaration;","tryCatchPattern":"try { JsonConvert.SerializeXmlNode(doc); }\ncatch (JsonSerializationException ex) when (ex.Message.Contains(\"Unexpected XmlNodeType when serializing nodes\"))\n{\n    throw new InvalidDataException(\"XML contains a node type the converter cannot serialize\", ex);\n}","preventionTips":["Load XML with DtdProcessing.Parse so entity references are expanded away.","Pre-walk the DOM and reject/normalize unsupported node types before serializing.","Keep custom IXmlNode implementations within the supported node-type set."],"tags":["serialization","converter","xml","node-type"],"analyzedSha":"4f73e74372445108d2c1bda37b36e6f5e43402e0","analyzedAt":"2026-08-07T06:10:08.596Z","schemaVersion":2},"datasetVersion":"2026-08-07T07:17:06.508Z"}