本文整理汇总了C#中System.Xml.Serialization.XmlRootAttribute类的典型用法代码示例。如果您正苦于以下问题:C# XmlRootAttribute类的具体用法?C# XmlRootAttribute怎么用?C# XmlRootAttribute使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
XmlRootAttribute类属于System.Xml.Serialization命名空间,在下文中一共展示了XmlRootAttribute类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Import
public ImportResult Import(Stream inputStream)
{
_log.Debug("Import started");
var root = new XmlRootAttribute("Results");
var serializer = new XmlSerializer(typeof(ExportObject[]), root);
var deserialized = (ExportObject[])serializer.Deserialize(inputStream);
_log.Debug("Imported {0} objects", deserialized.Length);
if (deserialized.Length == 0)
{
return new ImportResult(Enumerable.Empty<RmResource>(), Enumerable.Empty<RmResource>());
}
string primaryObjectsType = deserialized[0].ResourceManagementObject.ObjectType;
_log.Debug("Detected {0} as primary import type", primaryObjectsType);
var allImportedObjects = deserialized.Select(x => ConvertToResource(x))
.ToList();
var primaryObjects = allImportedObjects.Where(x => x.ObjectType == primaryObjectsType)
.ToList();
_log.Debug("Imported {0} primary objects", primaryObjects.Count);
return new ImportResult(primaryObjects, allImportedObjects);
}
示例2: WriteObject
public bool WriteObject(XPathResult result, XPathNavigator node, object value)
{
var rootOverride = new XmlRootAttribute(node.LocalName)
{
Namespace = node.NamespaceURI
};
var xml = new StringBuilder();
var settings = new XmlWriterSettings
{
OmitXmlDeclaration = true,
Indent = false
};
var namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
if (string.IsNullOrEmpty(node.NamespaceURI) == false)
{
var prefix = result.Context.AddNamespace(node.NamespaceURI);
namespaces.Add(prefix, node.NamespaceURI);
}
var serializer = new XmlSerializer(result.Type, rootOverride);
using (var writer = XmlWriter.Create(xml, settings))
{
serializer.Serialize(writer, value, namespaces);
writer.Flush();
}
node.ReplaceSelf(xml.ToString());
return true;
}
示例3: BothCounters
public void BothCounters()
{
using (XmlSerializerCache cache = new XmlSerializerCache())
{
string instanceName = PerfCounterManagerTests.GetCounterInstanceName(0);
using (PerformanceCounter instanceCounter = new PerformanceCounter(PerfCounterManagerTests.CATEGORY
, PerfCounterManagerTests.CACHED_INSTANCES_NAME
, instanceName
, true))
{
Assert.AreEqual(0, instanceCounter.RawValue);
using (PerformanceCounter hitCounter = new PerformanceCounter(PerfCounterManagerTests.CATEGORY
, PerfCounterManagerTests.SERIALIZER_HITS_NAME
, instanceName
, true))
{
Assert.AreEqual(0, hitCounter.RawValue);
XmlRootAttribute root = new XmlRootAttribute( "theRoot" );
XmlSerializer ser = cache.GetSerializer(typeof(SerializeMe), root);
Assert.AreEqual(1, instanceCounter.RawValue);
Assert.AreEqual(0, hitCounter.RawValue);
ser = cache.GetSerializer(typeof(SerializeMe), root);
Assert.AreEqual(1, instanceCounter.RawValue);
Assert.AreEqual(1, hitCounter.RawValue);
}
}
}
}
示例4: ProxyType
public ProxyType(Type type)
{
var envTypes = new List<Type>();
var methods =
(from method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public)
.Where(method => Attribute.IsDefined(method, typeof(ServiceMethodAttribute)))
select new
{
MethodName = method.Name,
ServiceAttribute = (ServiceMethodAttribute)Attribute.GetCustomAttribute(method, typeof(ServiceMethodAttribute))
}).ToArray();
var mappings = (from m in methods select new
{
MethodName = m.MethodName,
Action = m.ServiceAttribute.Action,
ArgsTypeIndex = AddOrGetIndexOfExistingType(envTypes, m.ServiceAttribute.ArgType),
ResultsTypeIndex = AddOrGetIndexOfExistingType(envTypes, m.ServiceAttribute.ReturnType)
}).ToArray();
var xmlRoot = new XmlRootAttribute("Command");
var envSerializers = envTypes.ConvertAll<XmlSerializer>(t => new XmlSerializer(t, xmlRoot));
foreach (var m in mappings)
{
var svcMethod = new ServiceMethodInfo()
{
MethodName = m.MethodName,
ServiceAction = m.Action,
ArgsSerializer = envSerializers[m.ArgsTypeIndex],
ResultsSerializer = envSerializers[m.ResultsTypeIndex]
};
_methods.Add(svcMethod.MethodName, svcMethod);
}
}
示例5: Map
private XmlTypeMapping Map(Type t, XmlRootAttribute root)
{
XmlReflectionImporter ri = new XmlReflectionImporter();
XmlTypeMapping tm = ri.ImportTypeMapping(t, root);
return tm;
}
示例6: Create
public object Create(object parent, object configContext, XmlNode section)
{
var xRoot = new XmlRootAttribute { ElementName = section.Name, IsNullable = true };
var ser = new XmlSerializer(GetType(), xRoot);
var xNodeReader = new XmlNodeReader(section);
return ser.Deserialize(xNodeReader);
}
示例7: XmlSerializer
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace) {
XmlReflectionImporter importer = new XmlReflectionImporter(overrides, defaultNamespace);
for (int i = 0; i < extraTypes.Length; i++)
importer.IncludeType(extraTypes[i]);
tempAssembly = GenerateTempAssembly(importer.ImportTypeMapping(type, root));
this.events.sender = this;
}
示例8: Serialize
/// <summary>
/// Serializes an object into an XML document
/// </summary>
/// <param name="obj">object to serialize</param>
/// <param name="rootAttribute">root attribute to use</param>
/// <param name="namespacePrefixes">namespace prefixes</param>
/// <returns>a string that contains the XML document</returns>
public static string Serialize(object obj, XmlRootAttribute rootAttribute, params XmlQualifiedName[] namespacePrefixes)
{
if (obj == null)
{
return null;
}
using (var textWriter = new StringWriterUTF8())
{
var type = obj.GetType();
var xmlAttributeOverrides = new XmlAttributeOverrides();
if (rootAttribute != null)
{
var xmlAttributes = new XmlAttributes();
xmlAttributes.XmlRoot = rootAttribute;
xmlAttributeOverrides.Add(type, xmlAttributes);
}
using (var xmWriter = XmlWriter.Create(textWriter, new XmlWriterSettings() { OmitXmlDeclaration = true }))
{
var namespaces = new XmlSerializerNamespaces();
if (namespacePrefixes != null)
{
foreach (var ns in namespacePrefixes)
{
namespaces.Add(ns.Name, ns.Namespace);
}
}
new XmlSerializer(type, xmlAttributeOverrides).Serialize(xmWriter, obj, namespaces);
}
return textWriter.ToString();
}
}
示例9: getRequestContent
public byte[] getRequestContent( string doctype, string root, Type type, object obj)
{
XmlSerializer serializer = null;
if (root == null)
{
//... root element will be the object type name
serializer = new XmlSerializer(type);
}
else
{
//... root element set explicitely
var xattribs = new XmlAttributes();
var xroot = new XmlRootAttribute(root);
xattribs.XmlRoot = xroot;
var xoverrides = new XmlAttributeOverrides();
xoverrides.Add(type, xattribs);
serializer = new XmlSerializer(type, xoverrides);
}
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = false;
settings.OmitXmlDeclaration = false;
settings.Encoding = new UTF8Encoding(false/*no BOM*/, true/*throw if input illegal*/);
XmlSerializerNamespaces xmlNameSpace = new XmlSerializerNamespaces();
xmlNameSpace.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
xmlNameSpace.Add("noNamespaceSchemaLocation", m_schemadir + "/" + doctype + "." + m_schemaext);
StringWriter sw = new StringWriter();
XmlWriter xw = XmlWriter.Create( sw, settings);
xw.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
serializer.Serialize(xw, obj, xmlNameSpace);
return settings.Encoding.GetBytes( sw.ToString());
}
示例10: Serialize
//users [LOGIN]
public static void Serialize(List<User> iList, string iFileName)
{
UsersCollection Coll = new UsersCollection();
foreach (User usr in iList)
{
Coll.uList.Add(usr);
}
XmlRootAttribute RootAttr = new XmlRootAttribute();
RootAttr.ElementName = "UsersCollection";
RootAttr.IsNullable = true;
XmlSerializer Serializer = new XmlSerializer(typeof(UsersCollection), RootAttr);
StreamWriter StreamWriter = null;
try
{
StreamWriter = new StreamWriter(iFileName);
Serializer.Serialize(StreamWriter, Coll);
}
catch (Exception Ex)
{
Console.WriteLine("Exception while writing into DB: " + Ex.Message);
}
finally
{
if (null != StreamWriter)
{
StreamWriter.Dispose();
}
}
}
示例11: Initialize
private void Initialize(Type type, string rootName, string rootNamespace, XmlSerializer xmlSerializer)
{
if (type == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("type");
}
_rootType = type;
_rootName = rootName;
_rootNamespace = rootNamespace == null ? string.Empty : rootNamespace;
_serializer = xmlSerializer;
if (_serializer == null)
{
if (_rootName == null)
_serializer = new XmlSerializer(type);
else
{
XmlRootAttribute xmlRoot = new XmlRootAttribute();
xmlRoot.ElementName = _rootName;
xmlRoot.Namespace = _rootNamespace;
_serializer = new XmlSerializer(type, xmlRoot);
}
}
else
_isSerializerSetExplicit = true;
//try to get rootName and rootNamespace from type since root name not set explicitly
if (_rootName == null)
{
XmlTypeMapping mapping = new XmlReflectionImporter(null).ImportTypeMapping(_rootType);
_rootName = mapping.ElementName;
_rootNamespace = mapping.Namespace;
}
}
示例12: Application_Start
protected void Application_Start()
{
log4net.Config.XmlConfigurator.Configure();
GlobalConfiguration.Configure(WebApiConfig.Register);
GlobalConfiguration.Configuration.Formatters.JsonFormatter.AddUriPathExtensionMapping("json", "application/json");
GlobalConfiguration.Configuration.Formatters.XmlFormatter.AddUriPathExtensionMapping("xml", "text/xml");
// Add a text/plain formatter (WebApiContrib also contains CSV and other formaters)
GlobalConfiguration.Configuration.Formatters.Add(new PlainTextFormatter());
XmlMediaTypeFormatter formatter = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
formatter.UseXmlSerializer = true;
// Set up serializer configuration for data object:
XmlRootAttribute studentPersonalsXmlRootAttribute = new XmlRootAttribute("LearnerPersonals") { Namespace = SettingsManager.ProviderSettings.DataModelNamespace, IsNullable = false };
ISerialiser<List<LearnerPersonal>> studentPersonalsSerialiser = SerialiserFactory.GetXmlSerialiser<List<LearnerPersonal>>(studentPersonalsXmlRootAttribute);
formatter.SetSerializer<List<LearnerPersonal>>((XmlSerializer)studentPersonalsSerialiser);
// Configure global exception loggers for unexpected errors.
GlobalConfiguration.Configuration.Services.Add(typeof(IExceptionLogger), new TraceExceptionLogger());
// Configure a global exception handler for unexpected errors.
GlobalConfiguration.Configuration.Services.Replace(typeof(IExceptionHandler), new GlobalUnexpectedExceptionHandler());
Trace.TraceInformation("********** Application_Start **********");
log.Info("********** Application_Start **********");
Register();
}
示例13: XmlMetadata
public XmlMetadata(Type type, XmlTypeAttribute xmlType, XmlRootAttribute xmlRoot, IEnumerable<Type> xmlIncludes)
{
Type = type;
XmlType = xmlType;
XmlRoot = xmlRoot;
XmlIncludes = xmlIncludes;
}
示例14: getRequestContent
public static byte[] getRequestContent(string doctype, string root, Type type, object obj)
{
var xattribs = new XmlAttributes();
var xroot = new XmlRootAttribute(root);
xattribs.XmlRoot = xroot;
var xoverrides = new XmlAttributeOverrides();
//... have to use XmlAttributeOverrides because .NET insists on the object name as root element name otherwise ([XmlRoot(..)] has no effect)
xoverrides.Add(type, xattribs);
XmlSerializer serializer = new XmlSerializer(type, xoverrides);
StringWriter sw = new StringWriter();
XmlWriterSettings wsettings = new XmlWriterSettings();
wsettings.OmitXmlDeclaration = false;
wsettings.Encoding = new UTF8Encoding();
XmlWriter xw = XmlWriter.Create(sw, wsettings);
xw.WriteProcessingInstruction("xml", "version='1.0' standalone='no'");
//... have to write header by hand (OmitXmlDeclaration=false has no effect)
xw.WriteDocType(root, null, doctype + ".sfrm", null);
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
//... trick to avoid printing of xmlns:xsi xmlns:xsd attributes of the root element
serializer.Serialize(xw, obj, ns);
return sw.ToArray();
}
示例15: environmentTypes_Serialisation
public void environmentTypes_Serialisation()
{
environmentType environmentType1;
using (FileStream xmlStream = File.OpenRead(environmentXmlFile))
{
environmentType1 = SerialiserFactory.GetXmlSerialiser<environmentType>().Deserialise(xmlStream);
}
Assert.AreEqual(environmentType1.sessionToken, "2e5dd3ca282fc8ddb3d08dcacc407e8a", true, "Session token does not match.");
environmentType environmentType2;
using (FileStream xmlStream = File.OpenRead(environmentXmlFile))
{
environmentType2 = SerialiserFactory.GetXmlSerialiser<environmentType>().Deserialise(xmlStream);
}
Assert.AreEqual(environmentType2.sessionToken, "2e5dd3ca282fc8ddb3d08dcacc407e8a", true, "Session token does not match.");
ICollection<environmentType> environmentTypes = new Collection<environmentType>
{
environmentType1,
environmentType2
};
XmlRootAttribute xmlRootAttribute = new XmlRootAttribute("environments") { Namespace = SettingsManager.ConsumerSettings.DataModelNamespace, IsNullable = false };
string xmlString = SerialiserFactory.GetXmlSerialiser<Collection<environmentType>>(xmlRootAttribute).Serialise((Collection<environmentType>)environmentTypes);
System.Console.WriteLine(xmlString);
environmentTypes = SerialiserFactory.GetXmlSerialiser<Collection<environmentType>>(xmlRootAttribute).Deserialise(xmlString);
System.Console.WriteLine("Number deserialised is " + environmentTypes.Count);
}