본문 바로가기

Troubleshoot

C# Token StartElement in state EndRootElement would result in an invalid XML document. Make sure that the ConformanceLevel setting is set to ConformanceLevel.Fragment or ConformanceLevel.Auto if you want to write an XML fragment.

XDocument Transformation 시 XmlWriter에서 아래와 같은 오류가 발생되었습니다.


영문의 경우 아래와 같습니다.
Token StartElement in state EndRootElement would result in an invalid XML document. Make sure that the ConformanceLevel setting is set to ConformanceLevel.Fragment or ConformanceLevel.Auto if you want to write an XML fragment.

국문의 경우에는 아래와 같습니다.
상태 EndRootElement의 토큰 StartElement은(는) XML 문서를 사용할 수 없게 할 수 있습니다. XML 단편을 쓰려면 ConformanceLevel 설정을 ConformanceLevel.Fragment 또는 ConformanceLevel.Auto로 설정해야 합니다.

소스는 아래와 같습니다.

#region // static string GetTransformation(this XDocument xDoc, string strXslPath) //
/// <summary>
/// XDocument에 Xsl를 트랜스포메이션 한 후 해당 데이터를 반환한다.
/// </summary>
/// <param name="xDoc">Xml Doc</param>
/// <param name="strXslPath">Xsl Path</param>
/// <returns>Transform Data</returns>
public static string GetTransformation(this XDocument xDoc, string strXslPath)
{
	string strResult = String.Empty;
	XslCompiledTransform xsl = new XslCompiledTransform(true);
	xsl.Load(strXslPath);

	using (var ms = new MemoryStream())
	{
		using (var writer = XmlWriter.Create(ms))
		{
			xsl.Transform(xDoc.CreateReader(), writer);

			writer.Flush();
			ms.Position = 0;

			strResult = Encoding.UTF8.GetString(ms.GetBuffer());
		}
	}

	return strResult;
}
#endregion


위 소스에서 XmlWriter 생성시 XmlWriterSettings 를 추가하여 해결 할 수 있습니다.

변경 된 소스는 아래와 같습니다.

#region // static string GetTransformation(this XDocument xDoc, string strXslPath) //
/// <summary>
/// XDocument에 Xsl를 트랜스포메이션 한 후 해당 데이터를 반환한다.
/// </summary>
/// <param name="xDoc">Xml Doc</param>
/// <param name="strXslPath">Xsl Path</param>
/// <returns>Transform Data</returns>
public static string GetTransformation(this XDocument xDoc, string strXslPath)
{
	string strResult = String.Empty;
	XslCompiledTransform xsl = new XslCompiledTransform(true);
	xsl.Load(strXslPath);

	using (var ms = new MemoryStream())
	{
		XmlWriterSettings settings = new XmlWriterSettings()
		{
			ConformanceLevel = ConformanceLevel.Auto
		};

		using (var writer = XmlWriter.Create(ms, settings))
		{
			xsl.Transform(xDoc.CreateReader(), writer);

			writer.Flush();
			ms.Position = 0;

			strResult = Encoding.UTF8.GetString(ms.GetBuffer());
		}
	}

	return strResult;
}
#endregion


이렇게 하면 에러를 수정할 수 있습니다.

이상입니다.

감사합니다.