XmlAttributeOverrides将属性附加到元素

时间:2012-11-28 18:11:48

标签: c# xml xml-serialization

我有以下代码抛出错误......

错误......

  

对于非数组类型,您可以使用以下属性:XmlAttribute,XmlText,XmlElement或XmlAnyElement。

代码(Go方法的最后一行抛出异常)......

    public void Go(Type typeToSerialize, object itemToSerialize)
    {
        Dictionary<string, bool> processedList = new Dictionary<string, bool>();
        XmlAttributeOverrides overrides = new XmlAttributeOverrides();

        AttachXmlTransforms(overrides, itemToSerialize.GetType(), processedList);

        s = new XmlSerializer(typeToSerialize, overrides);
    }

    private static void AttachXmlTransforms(XmlAttributeOverrides overrides, Type root,
        Dictionary<string, bool> processedList)
    {
        foreach (PropertyInfo pi in root.GetProperties())
        {
            string keyName = pi.DeclaringType + "-" + pi.Name;

            if ((pi.PropertyType == typeof(DateTime) || pi.PropertyType == typeof(DateTime?))
                && !processedList.ContainsKey(keyName))
            {
                XmlAttributes attributes = new XmlAttributes();

                attributes.XmlElements.Add(new XmlElementAttribute(pi.Name));
                //attributes.XmlAnyAttribute = new XmlAnyAttributeAttribute();
                attributes.XmlAttribute = new XmlAttributeAttribute("dval");

                //attributes.XmlIgnore = true;

                processedList.Add(keyName, true);


                overrides.Add(pi.DeclaringType, pi.Name, attributes);
            }

            if (pi.MemberType == MemberTypes.Property && !pi.PropertyType.IsPrimitive
                && pi.PropertyType.IsPublic && pi.PropertyType.IsClass
                && pi.PropertyType != typeof(DateTime))
            {
                AttachXmlTransforms(overrides, pi.PropertyType, processedList);
            }
        }
    }

我正在尝试仅将属性(dval)添加到DateTime元素(这是外部要求)...

从此......

   <CreatedDate>01/01/2012</CreatedDate>

对此...

   <CreatedDate dval="01/01/2012">01/01/2012</CreatedDate>

有没有办法将属性添加到普通的非数组类型元素?

2 个答案:

答案 0 :(得分:1)

我认为你在线上遇到了麻烦

attributes.XmlElements.Add(new XmlElementAttribute(pi.Name))

首先,根据命名惯例判断,我猜测XmlElements不是Xml元素,但它是集合元素。

此外,根据您的错误消息判断,XmlElements Add方法不会将您的XmlElementAttribute作为参数,而是需要XmlAttribute, XmlText, XmlElement, or XmlAnyElement.

答案 1 :(得分:0)

我最终以不同的方式处理这个......

1)将对象转换为XML

2)运行以下内容......

        using (MemoryStream memStm = new MemoryStream())
        {
            // Serialize the object using the standard DC serializer.
            s.WriteObject(memStm, graph);

            // Fix the memstream location.
            memStm.Seek(0, SeekOrigin.Begin);

            // Load the serialized document.
            XDocument document = XDocument.Load(memStm);

            foreach (KeyValuePair<string, ItemToAmend> kvp in _processedDateTimes)
            {
                // Locate the datetime objects.
                IEnumerable<XElement> t = from el in document.Descendants(XName.Get(kvp.Value.ProperyName, kvp.Value.PropertyNamespace))
                                          select el;

                // Add the attribute to each element.
                foreach (XElement e in t)
                {
                    string convertedDate = string.Empty;

                    if (!string.IsNullOrEmpty(e.Value))
                    {
                        DateTime converted = DateTime.Parse(e.Value);

                        convertedDate = string.Format(new MyBtecDateTimeFormatter(), "{0}", converted);
                    }

                    e.Add(new XAttribute(XName.Get("dval"), convertedDate));
                }
            }

            // Write the document to the steam.
            document.Save(writer);
        }