XmlValidatorApiController.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. using Microsoft.AspNetCore.Mvc;
  2. using LAPS_XMLQC_Service.Services;
  3. using System.IO;
  4. using System.Xml.Xsl;
  5. using System.Xml;
  6. using System;
  7. using System.Collections.Generic;
  8. namespace LAPS_XMLQC_Service.Controllers.XmlValidator
  9. {
  10. [Route("api/[controller]")]
  11. [ApiController]
  12. public class XmlValidatorApiController : ControllerBase
  13. {
  14. private readonly XmlValidatorService _xmlValidator;
  15. public XmlValidatorApiController(XmlValidatorService xmlValidatorService)
  16. {
  17. _xmlValidator = xmlValidatorService;
  18. }
  19. [HttpGet("document-path")]
  20. public ActionResult<string> GetDocumentPath(string documentType, string projectDefinitionId)
  21. {
  22. string filepath = _xmlValidator.GetDocumentPath(documentType, Convert.ToInt32(projectDefinitionId));
  23. return Ok(filepath);
  24. }
  25. /// <summary>
  26. /// Validates XML against a DTD file.
  27. /// </summary>
  28. /// <param name="xmlContent">The XML content as a string.</param>
  29. /// <param name="dtdFilePath">The path to the DTD file.</param>
  30. /// <returns>A list of validation errors or a success message.</returns>
  31. [HttpPost("validate-dtd")]
  32. public IActionResult ValidateXmlAgainstDtd([FromBody] XmlValidationRequest request)
  33. {
  34. if (string.IsNullOrEmpty(request.XmlContent) || string.IsNullOrEmpty(request.SchemaFilePath))
  35. {
  36. return BadRequest("XML content and DTD file path are required.");
  37. }
  38. if (!System.IO.File.Exists(request.SchemaFilePath))
  39. {
  40. return NotFound("DTD file not found at the specified path.");
  41. }
  42. var validationErrors = _xmlValidator.ValidateXmlAgainstDtd(request.XmlContent, request.SchemaFilePath);
  43. return Ok(validationErrors);
  44. }
  45. /// <summary>
  46. /// Validates XML against an XSD file.
  47. /// </summary>
  48. /// <param name="xmlContent">The XML content as a string.</param>
  49. /// <param name="xsdFilePath">The path to the XSD file.</param>
  50. /// <returns>A list of validation errors or a success message.</returns>
  51. [HttpPost("validate-xsd")]
  52. public IActionResult ValidateXmlAgainstXsd([FromBody] XmlValidationRequest request)
  53. {
  54. if (string.IsNullOrEmpty(request.XmlContent) || string.IsNullOrEmpty(request.SchemaFilePath))
  55. {
  56. return BadRequest("XML content and XSD file path are required.");
  57. }
  58. if (!System.IO.File.Exists(request.SchemaFilePath))
  59. {
  60. return NotFound("XSD file not found at the specified path.");
  61. }
  62. var validationErrors = _xmlValidator.ValidateXmlAgainstXsd(request.XmlContent, request.SchemaFilePath);
  63. return Ok(validationErrors);
  64. }
  65. [HttpPost("convert-text")]
  66. public IActionResult ConvertXmlToText([FromBody] XmlValidationRequest request)
  67. {
  68. try
  69. {
  70. var validationErrors = new List<string>();
  71. if (string.IsNullOrEmpty(request.XmlContent) || string.IsNullOrEmpty(request.SchemaFilePath))
  72. {
  73. return BadRequest("XML content and XSLT file path are required.");
  74. }
  75. if (!System.IO.File.Exists(request.SchemaFilePath))
  76. {
  77. return NotFound("XSLT file not found at the specified path.");
  78. }
  79. // Load XML content
  80. XmlDocument xmlDocument = new XmlDocument();
  81. xmlDocument.LoadXml(request.XmlContent);
  82. // Prepare output file path
  83. request.FileName = request.FileName + ".txt";
  84. string outputFilePath = Path.Combine(request.OutputPath.Replace(@"\IN", @"\OUT"), request.FileName);
  85. // Configure XmlWriterSettings to allow XML fragments
  86. XmlWriterSettings settings = new XmlWriterSettings
  87. {
  88. ConformanceLevel = ConformanceLevel.Fragment, // Allows fragments
  89. Indent = true // Optional: for better readability
  90. };
  91. // Apply the transformation
  92. XslCompiledTransform xslt = new XslCompiledTransform();
  93. xslt.Load(request.SchemaFilePath);
  94. using (StreamWriter writer = new StreamWriter(outputFilePath))
  95. using (XmlWriter xmlWriter = XmlWriter.Create(writer, settings)) // Use settings here
  96. {
  97. xslt.Transform(xmlDocument, xmlWriter);
  98. }
  99. // Read the generated file content
  100. string fileContent = string.Empty;
  101. using (StreamReader reader = new StreamReader(outputFilePath))
  102. {
  103. fileContent = reader.ReadToEnd();
  104. }
  105. if (validationErrors.Count == 0)
  106. {
  107. validationErrors.Add("XML is successfully transformed into a text file.");
  108. }
  109. // Return the file content as part of the response
  110. return Ok(new
  111. {
  112. Messages = validationErrors,
  113. FileContent = fileContent
  114. });
  115. }
  116. catch (XmlException ex)
  117. {
  118. return BadRequest($"Invalid XML: {ex.Message}");
  119. }
  120. catch (XsltException ex)
  121. {
  122. return BadRequest($"XSLT Error: {ex.Message}");
  123. }
  124. catch (Exception ex)
  125. {
  126. return BadRequest($"An error occurred: {ex.Message}");
  127. }
  128. }
  129. }
  130. // Model to capture XML and Schema content for validation
  131. public class XmlValidationRequest
  132. {
  133. public string XmlContent { get; set; }
  134. public string SchemaFilePath { get; set; }
  135. public string OutputPath { get; set; }
  136. public string FileName { get; set; }
  137. }
  138. }