2017-09-23 52 views
0

鉴于下面的一段XML代码:改变属性值<或>(“<' or '>”)

<SD GID="&lt;empty&gt;" T="2017-07-31T13:37:48Z">&lt;empty&gt;</SD> 

从I产生与XSD.EXE类XSD文件和用于反串行化相应的类/串行化这些元素是:

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] 
[System.SerializableAttribute()] 
[System.Diagnostics.DebuggerStepThroughAttribute()] 
[System.ComponentModel.DesignerCategoryAttribute("code")] 
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://autosar.org/schema/r4.0")] 
public partial class SD { 
    /// <remarks/> 
    [System.Xml.Serialization.XmlAttributeAttribute(DataType = "NMTOKEN")] 
    public string GID; 

    /// <remarks/> 
    [System.Xml.Serialization.XmlAttributeAttribute()] 
    public string S; 

    /// <remarks/> 
    [System.Xml.Serialization.XmlAttributeAttribute()] 
    public string T; 

    /// <remarks/> 
    [System.Xml.Serialization.XmlTextAttribute()] 
    public string Value; 
} 

由于它可以在下面的图片此系以及反序列化中可以看出,“<”和“>”字符被正确解码: Quickwatch

我只是想序列化回不改变内容,但翻译回下列方式这条线线:

<SD GID="_x003C_empty_x003E_" T="2017-07-31T13:37:48Z">&lt;empty&gt;</SD> 

所以在价值领域有正确的字符串,根据xml标准,但在GID属性中'<'和'>'没有正确转换。

的主要代码是非常简单的:

namespace MyXMLHandler 
{ 
    using System; 
    using System.IO; 
    using System.Linq; 
    using System.Text; 
    using System.Xml; 
    using System.Xml.Serialization; 

    internal class Program 
    { 
     private static void Main(string[] args) 
     { 
      MyType a = DeserializeObject(
       @"source.arxml"); 
      SerializeObject(
       @"source_SERIALIZED.arxml", 
       a); 
     } 

     private static MyType DeserializeObject(string filename) 
     { 
      var serializer = new XmlSerializer(typeof(MyType)); 
      XmlReaderSettings xmlReaderSettings = new XmlReaderSettings(); 
      StreamReader reader = new StreamReader(filename, Encoding.UTF8); 
      MyType i; 

      i = (MyType)serializer.Deserialize(reader); 

      return i; 
     } 

     private static void SerializeObject(string filename, MyType i) 
     { 
      var serializer = new XmlSerializer(typeof(MyType)); 
      Stream fs = new FileStream(filename, FileMode.Create); 
      var settings = new XmlWriterSettings(); 
      settings.Indent = true; 
      settings.IndentChars = " "; 
      settings.Encoding = Encoding.UTF8; 
      var writer = XmlWriter.Create(fs, settings); 

      serializer.Serialize(writer, i); 

      writer.Close(); 

     } 
    } 
} 

什么可以在属性的charachters的错译的原因是什么?

+0

不,它没有标记。 –

+0

如果您将删除'DataType =“NMTOKEN”'问题将被解决。 –

回答

1

NMTOKEN不能有效地包含<>(即使它们被作为字符引用转义),所以序列化程序已找到自己的方法将属性值转换为有效的NMTOKEN。

+0

完美的解决方案!非常感谢! ;) –

相关问题