为什么我在XML中获取<string>节点

时间:2015-05-28 09:07:13

标签: c# asp.net xml

Dim xtab As XElement = Nothing
Dim nodes = From nodeToTake In customUIXml.Descendants().Elements("tab") _
            Where nodeToTake.Attribute("label").Value = "MyTab"
            Select nodeToTake

For Each tab As XElement In nodes
    xtab = tab
Next

int i = 0;
foreach (string item in titl)
{
    //new instance of Data
    Type keyType = item.GetType();
    XmlSerializer keySerializer = GetTypeSerializer(keyType.AssemblyQualifiedName);
    i = i + 1;
    if (i % 2 == 0)
    {
        writer.WriteStartElement("tTime");
    }
    else
    {
        writer.WriteStartElement("tText");
    }
    if (keyType != typeof(string)) { writer.WriteAttributeString("type", keyType.AssemblyQualifiedName); }
    keySerializer.Serialize(writer, item);
    writer.WriteEndElement();
}

我将XML格式化为:

#region " GetTypeSerializer "

private static readonly Dictionary<string, XmlSerializer> _serializers = new Dictionary<string, XmlSerializer>();
private static readonly object _deadbolt = new object();
private XmlSerializer GetTypeSerializer(string type)
{
    if (!_serializers.ContainsKey(type))
    {
        lock (_deadbolt)
        {
            if (!_serializers.ContainsKey(type))
            {
                _serializers.Add(type,new XmlSerializer(Type.GetType(type)));

            }
        }
    }
    return _serializers[type];
}

#endregion

我有一个字符串,我正在创建XML文件但是 我无法知道这个字符串标签来自哪里?可能是它来自某个地方的keyType但是我没有得到它怎么样?我不希望此字符串节点出现在此XML

2 个答案:

答案 0 :(得分:0)

嗯,XmlSerializer类显式序列化文档,文档(格式良好)包含根元素。 因此,XmlSerializer似乎将typename作为根元素的element-Name。

答案 1 :(得分:0)

你的代码告诉序列化程序Serialize是一个string类型的元素,而不是只写文本。

使用XmlWriter.WriteString代替XmlSerializer.Serialize - 代替:

keySerializer.Serialize(writer, item);

使用

writer.WriteString(item);

具体来说,这个:

var titl = new List<string> {"aaa", "bbb", "ccc"};

int i = 0;
foreach (string item in titl)
{
    //new instance of Data
    i = i + 1;
    if (i % 2 == 0)
    {
        writer.WriteStartElement("tTime");
    }
    else
    {
        writer.WriteStartElement("tText");
    }
    writer.WriteString(item);
    writer.WriteEndElement();
}

会产生这个

<tText>aaa</tText>
<tTime>bbb</tTime>
<tText>ccc</tText>