Skip to content

Instantly share code, notes, and snippets.

@ormaaj
Created October 21, 2013 09:08
Show Gist options
  • Select an option

  • Save ormaaj/7080850 to your computer and use it in GitHub Desktop.

Select an option

Save ormaaj/7080850 to your computer and use it in GitHub Desktop.
validator
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using System.Reflection;
namespace xmlreader {
/// <summary>
/// GFB validator.
/// </summary>
class GFBValidator {
public const string MSBNamespaceURI = @"http://schemas.microsoft.com/developer/msbuild/2003";
public string MyXpath { get; private set; }
XPathDocument document;
XPathNavigator navigator;
XmlNamespaceManager manager;
// XDocument document;
/// <summary>
/// Validator.
/// </summary>
/// <param name="fileName">Path to xml</param>
/// <param name="XPathTest">XPath to match</param>
public GFBValidator(string fileName, string xPathTest) {
// document = XDocument.Load(fileName);
document = new XPathDocument(fileName);
navigator = document.CreateNavigator();
manager = new XmlNamespaceManager(navigator.NameTable);
manager.AddNamespace("m", MSBNamespaceURI);
MyXpath = xPathTest;
}
/// <summary>
/// Validates this instance.
/// </summary>
/// <param name="match">Supplied projectname to test against the attributes.</param>
/// <returns>bool indicating validation success.</returns>
public bool Validate(string match) {
string msg;
bool ret = true;
if (string.IsNullOrEmpty(match)) {
msg = string.Format("No project name specified. Must supply a valid non-empty project.");
ret = false;
} else {
IEnumerable<IXPathNavigable> attList = ((IEnumerable)navigator.Select(MyXpath, manager)).Cast<IXPathNavigable>();
try {
msg = string.Format("Project name {0} is valid.", attList.Single(x => x.ToString().Equals(match, StringComparison.InvariantCultureIgnoreCase)));
ret = true;
} catch (System.InvalidOperationException) {
msg = string.Format("No element matching {0}.", match);
ret = false;
}
}
Console.WriteLine(msg);
return ret;
}
}
class Program {
static int Main(string[] args) {
string FilenameTest = @"/home/smorg/doc/projects/cs/xmldata/GFBList.config.xml";
string XPathTest = "//m:ItemGroup/m:Name/@Include";
var obj = new GFBValidator(FilenameTest, XPathTest);
Console.WriteLine(obj.Validate("projname"));
Console.Read();
return 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment