Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support namespace analysis #662

Merged
merged 2 commits into from
Sep 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/dev/impl/DevToys/DevToys.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -161,12 +161,14 @@
<Compile Include="ViewModels\Tools\Text\StringEscapeUnescape\StringEscapeUnescapeToolProvider.cs" />
<Compile Include="ViewModels\Tools\Text\StringEscapeUnescape\StringEscapeUnescapeToolViewModel.cs" />
<Compile Include="ViewModels\Tools\Text\TextGroupToolProvider.cs" />
<Compile Include="ViewModels\Tools\Text\XmlValidator\NamespaceHelper.cs" />
<Compile Include="ViewModels\Tools\Text\XmlValidator\Parsing\ParserBase.cs" />
<Compile Include="ViewModels\Tools\Text\XmlValidator\Parsing\ParsingResultBase.cs" />
<Compile Include="ViewModels\Tools\Text\XmlValidator\Parsing\XmlParser.cs" />
<Compile Include="ViewModels\Tools\Text\XmlValidator\Parsing\XmlParsingResult.cs" />
<Compile Include="ViewModels\Tools\Text\XmlValidator\Parsing\XsdParser.cs" />
<Compile Include="ViewModels\Tools\Text\XmlValidator\Parsing\XsdParsingResult.cs" />
<Compile Include="ViewModels\Tools\Text\XmlValidator\XmlNamespace.cs" />
<Compile Include="ViewModels\Tools\Text\XmlValidator\XmlValidatorToolProvider.cs" />
<Compile Include="ViewModels\Tools\Text\XmlValidator\XmlValidatorToolViewModel.cs" />
<Compile Include="Views\Tools\AllTools\AllToolsToolPage.xaml.cs">
Expand Down
1 change: 0 additions & 1 deletion src/dev/impl/DevToys/Helpers/XmlHelper.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
#nullable enable

using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
Expand Down
15 changes: 15 additions & 0 deletions src/dev/impl/DevToys/LanguageManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3448,5 +3448,20 @@ public class XmlValidatorStrings : ObservableObject
/// Gets the resource SearchKeywords.
/// </summary>
public string SearchKeywords => _resources.GetString("SearchKeywords");

/// <summary>
/// Gets the resource XmlNamespacesInconsistentMsg.
/// </summary>
public string XmlNamespacesInconsistentMsg => _resources.GetString("XmlNamespacesInconsistentMsg");

/// <summary>
/// Gets the resource XsdNamespacesInconsistentMsg.
/// </summary>
public string XsdNamespacesInconsistentMsg => _resources.GetString("XsdNamespacesInconsistentMsg");

/// <summary>
/// Gets the resource TargetNamespaceNotDefinedInXml.
/// </summary>
public string TargetNamespaceNotDefinedInXml => _resources.GetString("TargetNamespaceNotDefinedInXml");
}
}
9 changes: 9 additions & 0 deletions src/dev/impl/DevToys/Strings/en-US/XmlValidator.resw
Original file line number Diff line number Diff line change
Expand Up @@ -144,4 +144,13 @@
<data name="SearchKeywords" xml:space="preserve">
<value>XML XSD Validate</value>
</data>
<data name="XmlNamespacesInconsistentMsg" xml:space="preserve">
<value>Validation result will always be 'valid' since the XML does not define these namespace(s) defined in the XSD: {0}</value>
</data>
<data name="XsdNamespacesInconsistentMsg" xml:space="preserve">
<value>Validation result will always be 'valid' since the XSD does not define these namespace(s) defined in the XML: {0}</value>
</data>
<data name="TargetNamespaceNotDefinedInXml" xml:space="preserve">
<value>Validation result will potentially always be 'valid' since the XML does not reference the following "targetNamespace" defined in the XSD: {0}</value>
</data>
</root>
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using DevToys.ViewModels.Tools.XmlValidator.Parsing;

namespace DevToys.ViewModels.Tools.XmlValidator
{
internal static class NamespaceHelper
{
/// <summary>
/// Identifies namespaces used within the XML data but not defined in the XSD schema.
/// </summary>
/// <param name="xsdParsingResult">XSD parsing result</param>
/// <param name="xmlParsingResult">XML parsing result</param>
/// <returns>The missing namespaces.</returns>
public static IEnumerable<XmlNamespace> GetMissingNamespacesInXsd(XsdParsingResult xsdParsingResult, XmlParsingResult xmlParsingResult)
{
IEnumerable<XmlNamespace> clearedXdsNamespaces = GetNamespacesFromXsd(xsdParsingResult);
IEnumerable<XmlNamespace> xmlNamespaces = xmlParsingResult.Namespaces;

// filter targetNamespace
if (xsdParsingResult.TargetNamespace is not null)
{
xmlNamespaces = xmlNamespaces.Where(xns => !string.Equals(xns.Uri, xsdParsingResult.TargetNamespace, StringComparison.InvariantCultureIgnoreCase));
}

return xmlNamespaces.Where(ns => clearedXdsNamespaces.Contains(ns) == false);
}

/// <summary>
/// Identifies namespaces defined within the XSD schema but not used in the XML data.
/// </summary>
/// <param name="xsdParsingResult">XSD parsing result</param>
/// <param name="xmlParsingResult">XML parsing result</param>
/// <returns>The missing namespaces</returns>
public static IEnumerable<XmlNamespace> GetMissingNamespacesInXml(XsdParsingResult xsdParsingResult, XmlParsingResult xmlParsingResult)
{
IEnumerable<XmlNamespace> clearedXdsNamespaces = GetNamespacesFromXsd(xsdParsingResult);
IEnumerable<XmlNamespace> xmlNamespaces = xmlParsingResult.Namespaces;

return clearedXdsNamespaces.Where(ns => xmlNamespaces.Contains(ns) == false);
}

public static bool DetectMissingTargetNamespaceInXml(XsdParsingResult xsdParsingResult, XmlParsingResult xmlParsingResult, out string? missingTargetNamespaceUri)
{
bool isTargetNamespaceDefinedInXml = xmlParsingResult.Namespaces.Select(ns => ns.Uri).Any(uri => string.Equals(uri, xsdParsingResult.TargetNamespace));
if (isTargetNamespaceDefinedInXml)
{
missingTargetNamespaceUri = null;
return false;
}

missingTargetNamespaceUri = xsdParsingResult.TargetNamespace;
return true;
}

private static IEnumerable<XmlNamespace> GetNamespacesFromXsd(XsdParsingResult xsdParsingResult)
{
static bool IsDefaultXsdNamespace(XmlNamespace xmlNamespace) => xmlNamespace.Prefix.StartsWith("xs", StringComparison.InvariantCultureIgnoreCase);

// return namespaces without default XSD namespace (xmlns:xs="http://www.w3.org/2001/XMLSchema")
return xsdParsingResult.Namespaces.Where(xns => !IsDefaultXsdNamespace(xns));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using System.Xml.XPath;

namespace DevToys.ViewModels.Tools.XmlValidator.Parsing
{
internal abstract class ParserBase<TResult>
internal abstract class ParserBase<TResult> where TResult : ParsingResultBase
{
protected readonly string Source;
private readonly List<string> _validationWarnings;
Expand All @@ -23,8 +27,26 @@ protected ParserBase(string source)
_validationErrors = new List<string>();
}

internal abstract TResult Parse(string content);
internal TResult Parse(string content)
{
TResult result = ParsingOperation(content);

XDocument document;
try
{
document = XDocument.Parse(content);
}
catch
{
document = new XDocument();
}

result.Namespaces = GetAllNamespaces(document);
return result;
}

protected abstract TResult ParsingOperation(string content);

internal void ValidationErrorCallBack(object sender, ValidationEventArgs e)
{
string information =
Expand Down Expand Up @@ -55,5 +77,19 @@ protected string GetValidationMessages()
messages += string.Join(Environment.NewLine, _validationWarnings);
return messages;
}

/// <summary>
/// Extracts all <c>xmlns</c> namespaces from a given <paramref name="xmlDocument"/>.
/// </summary>
/// <param name="xmlDocument">XML document containing namespaces.</param>
/// <returns></returns>
private static IEnumerable<XmlNamespace> GetAllNamespaces(XDocument xmlDocument)
{
XPathNavigator? navigator = xmlDocument.CreateNavigator();
navigator.MoveToFollowing(XPathNodeType.Element);

IDictionary<string, string> namespaces = navigator.GetNamespacesInScope(XmlNamespaceScope.ExcludeXml) ?? new Dictionary<string, string>();
return namespaces.Select(pair => new XmlNamespace(pair.Key, pair.Value)).ToList();
}
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
#nullable enable

using System.Collections.Generic;

namespace DevToys.ViewModels.Tools.XmlValidator.Parsing
{
internal record ParsingResultBase
{
internal bool IsValid { get; set; }
internal string? ErrorMessage { get; set; }
internal IEnumerable<XmlNamespace> Namespaces { get; set; } = new List<XmlNamespace>();
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
#nullable enable

using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using DevToys.Helpers;

namespace DevToys.ViewModels.Tools.XmlValidator.Parsing
{
Expand All @@ -15,7 +17,7 @@ internal XmlParser(string source, XmlSchemaSet xsdSchema) : base(source)
_xsdSchema = xsdSchema;
}

internal override XmlParsingResult Parse(string content)
protected override XmlParsingResult ParsingOperation(string content)
{
XDocument xmlFile = new();
try
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,15 @@ public XsdParser(string source) : base(source)
{
}

internal override XsdParsingResult Parse(string xsdContent)
protected override XsdParsingResult ParsingOperation(string xsdContent)
{
XmlSchema xmlSchema;
string? targetNamespace;
try
{
xmlSchema = XmlSchema.Read(new XmlTextReader(new StringReader(xsdContent)), ValidationErrorCallBack);
using StringReader reader = new(xsdContent);
xmlSchema = XmlSchema.Read(reader, ValidationErrorCallBack);
targetNamespace = string.Equals(xmlSchema.TargetNamespace, string.Empty) ? null : xmlSchema.TargetNamespace;
}
catch (XmlException ex)
{
Expand All @@ -36,7 +39,8 @@ internal override XsdParsingResult Parse(string xsdContent)
XmlSchemaSet schema = new();
schema.Add(xmlSchema);
schema.Compile();
return new XsdParsingResult {IsValid = true, SchemaSet = schema};

return new XsdParsingResult {IsValid = true, SchemaSet = schema, TargetNamespace = targetNamespace};
}

private static XsdParsingResult GetInvalidParsingResult(string source, int lineNumber, int linePosition,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ namespace DevToys.ViewModels.Tools.XmlValidator.Parsing
{
internal record XsdParsingResult : ParsingResultBase
{
internal string? TargetNamespace { get; set; }
internal XmlSchemaSet? SchemaSet { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using System;

namespace DevToys.ViewModels.Tools.XmlValidator
{
public record XmlNamespace(string Prefix, string Uri)
{
public string Prefix { get; } = Prefix ?? throw new ArgumentNullException(nameof(Prefix));
public string Uri { get; } = Uri ?? throw new ArgumentNullException(nameof(Uri));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using Windows.UI.Xaml.Controls;
using DevToys.Api.Tools;
using DevToys.Core.Threading;
using DevToys.Shared.Api.Core;

namespace DevToys.ViewModels.Tools.XmlValidator
Expand Down
Loading