Skip to content

Instantly share code, notes, and snippets.

@tmori3y2
Last active May 25, 2017 00:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmori3y2/869bed18ba500a5786d3688339c11fc5 to your computer and use it in GitHub Desktop.
Save tmori3y2/869bed18ba500a5786d3688339c11fc5 to your computer and use it in GitHub Desktop.
TestXDocWriteTo linqpad script
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:element name="test" type="testType" />
<xs:complexType name="testType">
<xs:sequence>
<xs:element name="uri" minOccurs="0" maxOccurs="unbounded" type="xs:anyURI" />
<xs:element name="uuid" minOccurs="0" maxOccurs="unbounded" type="uuid" />
<xs:element name="list" minOccurs="0" maxOccurs="unbounded" type="decimalList" />
</xs:sequence>
<xs:attribute name="uriA" type="xs:anyURI" />
<xs:attribute name="uuidA" type="uuid" />
<xs:attribute name="listA" type="decimalList" />
</xs:complexType>
<xs:simpleType name="uuid">
<xs:restriction base="xs:string">
<xs:pattern value="([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="decimalList">
<xs:list itemType="xs:decimal" />
</xs:simpleType>
</xs:schema>
<Query Kind="Program">
<Output>DataGrids</Output>
<Reference>&lt;RuntimeDirectory&gt;\System.Xml.Serialization.dll</Reference>
<Namespace>System.Globalization</Namespace>
<Namespace>System.IO</Namespace>
<Namespace>System.Linq</Namespace>
<Namespace>System.Text</Namespace>
<Namespace>System.Xml</Namespace>
<Namespace>System.Xml.Linq</Namespace>
<Namespace>System.Xml.Schema</Namespace>
<Namespace>System.Xml.Serialization</Namespace>
</Query>
// LinqPad 5で実行可能な C# script.
// 開発環境が無くても実行できます.
// 以下からダウンロードできます:
// https://www.linqpad.net/
// OS: Windows 7 sp1 or higher
// .NET Framework: 4.6 or higher
// Windows 10には含まれています.
// Windows 7 sp1/8.1は以下からダウンロードしてください:
// https://www.microsoft.com/ja-jp/download/details.aspx?id=53344
void Main()
{
var test = new Test()
{
UriA = new Uri("http://hatenablog.com"),
Uri = new Uri("http://hatenablog.com"),
UuidA = Guid.NewGuid(),
Uuid = Guid.NewGuid()
};
test.DecimalList.AddRange(new decimal[] { 1.0m, 2.00m, 3.001m });
test.DecimalListA.AddRange(new decimal[] { 1.001m, 2.00m, 3.0m });
test.Dump();
var xmlDoc = test.ToXDocument("");
xmlDoc.Dump();
var xsdName = $"{Util.CurrentQuery.Location}\\test.xsd";
xmlDoc.Validate("", xsdName);
var xml = xmlDoc.WriteXml();
xml.Dump();
XDocument.Parse(xml).Dump();
var fileName = $"{Util.CurrentQuery.Location}\\TestXDocumentWriteTo.xml";
xmlDoc.WriteTo(fileName);
var back = xml.XmlDeserialize<Test>("");
back.Dump();
//Process.Start(fileName);
}
// Define other methods and classes here
[XmlType("testType")]
[XmlRoot("test")]
public class Test
{
private static CultureInfo culture = CultureInfo.InvariantCulture;
private static NumberStyles style = NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint;
[XmlAttribute("uriA", DataType = "anyURI")]
public string UriAString
{
get { return UriA?.ToString(); }
set { UriA = ToUri(value); }
}
[XmlElement("uri", DataType = "anyURI")]
public string UriString
{
get { return Uri?.ToString(); }
set { Uri = ToUri(value); }
}
[XmlAttribute("uuidA")]
public string UuidAString
{
get { return UuidA?.ToString("D"); }
set { UuidA = ToGuid(value, "D"); }
}
[XmlElement("uuid")]
public string UuidString
{
get { return Uuid?.ToString("D"); }
set { Uuid = ToGuid(value, "D"); }
}
[XmlAttribute("listA")]
public string DecimalListAString
{
get { return ToListString(DecimalListA, "N3"); }
set { DecimalListA.Clear(); DecimalListA.AddRange(ToDecimalList(value)); }
}
[XmlElement("list")]
public string DecimalListString
{
get { return ToListString(DecimalList, "N2"); }
set { DecimalList.Clear(); DecimalList.AddRange(ToDecimalList(value)); }
}
[XmlIgnore]
public Uri UriA { get; set; }
[XmlIgnore]
public Uri Uri { get; set; }
[XmlIgnore]
public Guid? UuidA { get; set; }
[XmlIgnore]
public Guid? Uuid { get; set; }
[XmlIgnore]
public List<decimal> DecimalListA { get; } = new List<decimal>();
[XmlIgnore]
public List<decimal> DecimalList { get; } = new List<decimal>();
public static Uri ToUri(string uriString) => (uriString != null) ? new Uri(uriString, UriKind.RelativeOrAbsolute) : null;
public static Guid? ToGuid(string uuidString, string format) => (uuidString != null) ? (Guid?)Guid.ParseExact(uuidString, format) : null;
public static string ToListString(List<decimal> list, string format) => list.Select(item => item.ToString(format, culture))?.Aggregate((output, item) => $"{output} {item}");
public static IEnumerable<decimal> ToDecimalList(string listString) => listString?.Split(" ".ToCharArray()).Select(item => decimal.Parse(item, style, culture));
}
public static class XmlSerializeHelper
{
public static string XmlSerialize<T>(this T source, string defaultNamespace)
{
if (source == null)
{
return null;
}
var encoding = new UTF8Encoding(false);
var settings = new XmlWriterSettings();
settings.Encoding = encoding;
settings.Indent = true;
string xml = null;
MemoryStream stream = null;
try
{
var serializer = new XmlSerializer(typeof(T), defaultNamespace);
stream = new MemoryStream();
using (var writer = XmlWriter.Create(stream, settings))
{
serializer.Serialize(writer, source);
}
var bytes = stream.ToArray();
xml = encoding.GetString(bytes, 0, bytes.Length);
}
finally
{
stream?.Dispose();
}
return xml;
}
public static XDocument ToXDocument<T>(this T source, string defaultNamespace)
{
if (source == null)
{
return null;
}
XDocument document = new XDocument();
using (var writer = document.CreateWriter())
{
var serializer = new XmlSerializer(typeof(T), defaultNamespace);
serializer.Serialize(writer, source);
}
return document;
}
public static T XmlDeserialize<T>(this string xml, string defaultNamespace)
{
if (string.IsNullOrEmpty(xml))
{
return default(T);
}
var encoding = new UTF8Encoding(false);
var settings = new XmlReaderSettings();
var byteArray = encoding.GetBytes(xml);
T target = default(T);
MemoryStream stream = null;
try
{
var serializer = new XmlSerializer(typeof(T), defaultNamespace);
stream = new MemoryStream(byteArray);
using (var reader = XmlReader.Create(stream, settings))
{
target = (T)serializer.Deserialize(reader);
}
}
finally
{
stream?.Dispose();
}
return target;
}
public static string WriteXml(this XDocument document)
{
var encoding = new UTF8Encoding(false);
string xml = null;
MemoryStream stream = null;
try
{
stream = new MemoryStream();
using (var writer = new StreamWriter(stream, encoding))
{
document.Save(writer);
}
var bytes = stream.ToArray();
xml = encoding.GetString(bytes, 0, bytes.Length);
}
finally
{
stream?.Dispose();
}
return xml;
}
public static void WriteTo(this XDocument document, string fileName)
{
var encoding = new UTF8Encoding(false);
var settings = new XmlWriterSettings();
settings.Encoding = encoding;
settings.Indent = true;
using (var writer = XmlWriter.Create(fileName, settings))
{
document.WriteTo(writer);
}
}
public static void Validate(this XDocument document, string defaultNamespace, string xsdPath)
{
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add(defaultNamespace, xsdPath);
document.Validate(schemas, ValidationCallBack);
}
public static void ValidationCallBack(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Error)
{
Console.WriteLine("Error: " + args.Message);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment