Десериализовать с помощью XmlSerializer файл XML, который может иметь или не иметь установленный xmlns.C#

Место общения программистов C#
Ответить
Anonymous
 Десериализовать с помощью XmlSerializer файл XML, который может иметь или не иметь установленный xmlns.

Сообщение Anonymous »

Я создал классы C# с целевым пространством имен, теперь я хочу использовать этот тип с XML-файлом, который может иметь или не иметь установленный корневой атрибут xmlns.
Я изменил описание моего вопроса, чтобы включить воспроизводимый случай.
Мой класс корневого элемента выглядит следующим образом (измененный на основе сгенерированного класса):

Код: Выделить всё

namespace TestXmlSerializer
{
/// 
/// 
This is the root object of the XML data. It defines the entire DF
/// This is the root object of the XML data. It defines the entire DF
/// 
[System.ComponentModel.DescriptionAttribute("This is the root object of the XML data. It defines the entire DF")]
[System.CodeDom.Compiler.GeneratedCodeAttribute("XmlSchemaClassGenerator", "2.0.662.0")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute("dfType", Namespace = "http://www.company.com/a661")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlRootAttribute("a661_df", Namespace = "http://www.company.com/a661")]
public partial class DfType : ElementType
{
/// 
/// Initializes a new instance of the  class.
/// 
public DfType()
{
this._a661_Layer = new System.Collections.ObjectModel.Collection();
}

[System.Xml.Serialization.XmlIgnoreAttribute()]
private System.Collections.ObjectModel.Collection _a661_Layer;

[System.ComponentModel.DataAnnotations.RequiredAttribute()]
[System.Xml.Serialization.XmlElementAttribute("a661_layer")]
public System.Collections.ObjectModel.Collection A661_Layer
{
get
{
return this._a661_Layer;
}
private set
{
this._a661_Layer = value;
}
}

/// 
/// this is the name of the DF. It corresponds to the name of the file (not including file extension). Present in the XML Definition File only
/// To help enforce sensible names in data.
/// Minimum length: 1.
/// Maximum length: 128.
/// 
[System.ComponentModel.DescriptionAttribute("this is the name of the DF. It corresponds to the name of the file (not including" +
" file extension).  Present in the XML Definition File only")]
[System.ComponentModel.DataAnnotations.MinLengthAttribute(1)]
[System.ComponentModel.DataAnnotations.MaxLengthAttribute(128)]
[System.Xml.Serialization.XmlAttributeAttribute("name")]
public string Name { get; set; }

}

[System.CodeDom.Compiler.GeneratedCodeAttribute("XmlSchemaClassGenerator", "2.0.662.0")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute("elementType", Namespace = "http://www.company.com/a661")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(DfType))]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(LayerType))]
public partial class ElementType
{

[System.Xml.Serialization.XmlIgnoreAttribute()]
private System.Collections.ObjectModel.Collection _any;

[System.Xml.Serialization.XmlAnyElementAttribute()]
public System.Collections.ObjectModel.Collection Any
{
get
{
return this._any;
}
private set
{
this._any = value;
}
}

/// 
/// Gets a value indicating whether the Any collection is empty.
/// 
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool AnySpecified
{
get
{
return (this.Any.Count != 0);
}
}

/// 
/// Initializes a new instance of the  class.
/// 
public ElementType()
{
this._any = new System.Collections.ObjectModel.Collection();
this._anyAttribute = new System.Collections.ObjectModel.Collection();
}

[System.Xml.Serialization.XmlIgnoreAttribute()]
private System.Collections.ObjectModel.Collection _anyAttribute;

[System.ComponentModel.DataAnnotations.RequiredAttribute()]
[System.Xml.Serialization.XmlAnyAttributeAttribute()]
public System.Collections.ObjectModel.Collection AnyAttribute
{
get
{
return this._anyAttribute;
}
private set
{
this._anyAttribute = value;
}
}
}

[System.ComponentModel.DescriptionAttribute("Defines a layer")]
[System.CodeDom.Compiler.GeneratedCodeAttribute("XmlSchemaClassGenerator", "2.0.662.0")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute("layerType", Namespace = "http://www.company.com/a661")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class LayerType : ElementType
{

/// 
/// Initializes a new instance of the  class.
/// 
public LayerType()
{
}

/// 
/// present in the XML Definition variant of the file only. May be used for descriptive or other purposes.
/// To help enforce sensible names in data.
/// Minimum length: 1.
/// Maximum length: 128.
/// 
[System.ComponentModel.DescriptionAttribute("present in the XML Definition variant of the file only.  May be used for descripti" +
"ve or other purposes.")]
[System.ComponentModel.DataAnnotations.MinLengthAttribute(1)]
[System.ComponentModel.DataAnnotations.MaxLengthAttribute(128)]
[System.Xml.Serialization.XmlAttributeAttribute("name")]
public string Name { get; set; }
}

}
Я попробовал следующий код десериализации:

Код: Выделить всё

namespace TestXmlSerializer
{
internal class Program
{
static void Main(string[] args)
{
if (args.Length == 1 )
{
LoadDefinitionFile(args[0]);
} else
{
Console.WriteLine("program ");
}
}
private static DfType LoadDefinitionFile(string path)
{
// Read df as text
string df = File.ReadAllText(path);

// Dump bytes of patched df file
byte[] dfBytes = Encoding.ASCII.GetBytes(df);

// Deserialize
// Load input file
using MemoryStream memoryStream = new MemoryStream(dfBytes);

// Create Reader
XmlReader xmlReader = new XmlTextReader(memoryStream);
// Load xml Model
XmlSerializer serializer = new XmlSerializer(typeof(DfType));

// Deserialization
return (DfType)serializer.Deserialize(xmlReader);
}
}
}
Я опробовал пример программы на следующих примерах XML-файлов:
  • с xmlns
  • без xmlns
Когда я запускаю пример программы с помощью 1), кажется, что она выполняет свою работу, но когда я запускаю ее с помощью 2), она выдает мне исключение:

Код: Выделить всё

Unhandled exception. System.InvalidOperationException: There is an error in XML document (2, 2).
---> System.InvalidOperationException:  was not expected.
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderDfType.Read5_a661_df()
История этого вопроса такова, что он работоспособен в мире Java с помощью SAXParser, где вы можете указать схему, которой должен следовать ваш XML-файл.
У меня есть Java-редактор с историей, самый простой способ — заставить наши XML-файлы работать с генератором C#.
Как правильно переопределить корневое пространство имен при десериализации с помощью XmlSerializer?>

Подробнее здесь: https://stackoverflow.com/questions/798 ... e-xmlns-se
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»