Заранее спасибо.
Я знаю, что есть много вопросов, похожих на то, что я делаю, и я попробовал большинство решений, предложенных на этом и других сайтах.Но я не могу объединить две мои проблемы вместе.
У меня есть файл xsd, и я сериализуюсь в C # с помощью xsd.exe в Visual Studio.Теперь я хотел бы десериализовать XML обратно в объект.Я страдаю уже почти два дня.Я не могу успешно десериализовать документ.Между каждой строкой много нежелательных пробелов, поэтому я использую настройки, чтобы игнорировать эти пробелы.Я использую XML-файл в кодировке UTF-8.
Я пробовал много разных способов объединить настройки и использовать StreamReader, но мне кажется, что я не могу использовать оба одновременно.
Если я просто использую настройки и программу чтения строк, я получу:
There is an error in XML document (1, 1).
Если я использую настройки и streamReader, я получу:
"Instance validation error: 'DoS: resource consumption\n\t\t\t\t\t\t(CPU)' is not a valid value for Impact_Type."}
I 'Я не слишком уверен, как объединить оба вместе.
Это мой код для десериализации документа.
String file = @"C:\Documents and Settings\YYC\Desktop\cwec_v2.1\cwec_v2.1.xml";
//var lines = File.ReadAllText(file);
//var replace = Regex.Replace(lines, @"\s{2,}", "", RegexOptions.Multiline);
//File.WriteAllText(file, replace);
XmlReaderSettings settings = new XmlReaderSettings();
//settings.ConformanceLevel = ConformanceLevel.Fragment;
settings.IgnoreComments = true;
settings.IgnoreProcessingInstructions = true;
settings.IgnoreWhitespace = true;
settings.CloseInput = true;
XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());
XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);
//XmlReader reader = XmlReader.Create(new StreamReader(file), settings, context);
XmlReader reader = XmlReader.Create(new StringReader(file), settings, context);
Weakness_Catalog wC = (Weakness_Catalog)xS.Deserialize(reader);
Ниже я предоставляю часть кода XML, C # и xsd для справки.
Это часть файла XML:
<?xml version="1.0" encoding="UTF-8"?>
<Weakness_Catalog Catalog_Name="CWE" Catalog_Version="2.1" Catalog_Date="2011-09-13"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://cwe.mitre.org/data/xsd/cwe_schema_v5.1.xsd">
<Views>
<View ID="1000" Name="Research Concepts" Status="Draft">
<View_Structure>Graph</View_Structure>
....
<View_Audience>
<Audience>
<Stakeholder>Academic_Researchers</Stakeholder>
<Stakeholder_Description>
<Text>This view provides an organizational structure for weaknesses that is
different than the approaches undertaken by taxonomies such as Seven
Pernicious Kingdoms.</Text>
</Stakeholder_Description>
Это часть кода c #, созданного xsd.exe
using System.Xml.Serialization;
//
// This source code was auto-generated by xsd, Version=4.0.30319.1.
//
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class Weakness_Catalog {
private View[] viewsField;
private Category[] categoriesField;
private Weakness[] weaknessesField;
private Compound_Element[] compound_ElementsField;
private string catalog_NameField;
private string catalog_VersionField;
private System.DateTime catalog_DateField;
private bool catalog_DateFieldSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("View", IsNullable=false)]
public View[] Views {
get {
return this.viewsField;
}
set {
this.viewsField = value;
}
}
......
Это часть файла XSD
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
attributeFormDefault="unqualified">
<xs:element name="Weakness_Catalog">
<xs:annotation>
<xs:documentation> The Weakness_Catalog structure represents a collection of software
security issues (flaws, faults, bugs, vulnerabilities, weaknesses, etc). The name
used by CWE is usually "CWE". However, if this collection is a subset of CWE, then a
more appropriate name should be used. It has two required attributes: Catalog_Name
and Catalog_Version.</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element name="Views">
<xs:annotation>
<xs:documentation> The Views structure contains zero or more View elements.
Each View element represents a perspective with which one might look at
the weaknesses in CWE. CWE-699 Development View and CWE-1000 Research
View are two examples of Views. </xs:documentation>
</xs:annotation>
<xs:complexType>
.....
РЕДАКТИРОВАТЬ:
Я получил XSD-файл из "http://cwe.mitre.org/data/xsd/cwe_schema_v5.1.xsd"
Я получил XML-файл из" http://cwe.mitre.org/data/xml/cwec_v2.1.xml.zip"