构造xml文件:该文档已经有一个'DocumentElement'节点

时间:2016-04-04 08:14:10

标签: c# xml reflection

我正在尝试构建格式为

的.xml文件
<Orders>
    <Id type="System.Int32">1</Id>
    <OrderItems>
        <OrderItem>
            <Id type="System.Int32">321</Id>
            <Product type="System.String">Coffee</Product>
        </OrderItem>
    </OrderItems>
    <Client type="System.String">Johnny</Client>
<Orders>

对于Order型号:

public class Order
{
    public int Id { get; set; }
    public List<OrderItem> Products { get; set; }
    public string Client { get; set; }
}

在这里,我创建了Order元素

public void SaveToFile(IEnumerable<Order> elementsList)
    {
        XmlDocument xmlDoc = new XmlDocument();
        XmlDeclaration xmlDec = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", string.Empty);
        xmlDoc.PrependChild(xmlDec);
        XmlElement elemRoot = xmlDoc.CreateElement("Orders");
        xmlDoc.AppendChild(elemRoot);
        XmlHelper<Order> xmlHelper = new XmlHelper<Order>();
        foreach (var order in _orders)
        {
            xmlHelper.AddNodeToXmlDocument(xmlDoc, elemRoot, order);
        }
        xmlDoc.PreserveWhitespace = true;
        xmlDoc.Save(_filePath);
    }

在这里,我正在尝试构建子元素。它适用于Id和Client,但是当我尝试创建订单商品时,我在第document.AppendChild(elemRoot);

时收到此错误
public void AddNodeToXmlDocument(XmlDocument document, XmlElement rootElement, object myObject)
    {
        XmlElement myObjectElement = document.CreateElement(EntityFormatter.GetObjectName(myObject));
        foreach (var objectProperty in EntityFormatter.GetPropertiesAndValues(myObject))
        {
           if ((objectProperty.Value.GetType().FullName).ToString().Contains("System.Collections.Generic.List"))
            {
                Regex regex = new Regex(@"Models[.][A-Za-z]+");
                Match match = regex.Match(objectProperty.Value.ToString());
                var elemRoot = document.CreateElement(match.Value.Substring(7));
                document.AppendChild(elemRoot);
                foreach (var obj in objectProperty.Value.ToString())
                {
                    AddNodeToXmlDocument(document, elemRoot, obj);
                }
            }
            else
            {
                var elem = document.CreateElement(objectProperty.Key);
                elem.SetAttribute("type", objectProperty.Value.GetType().FullName);
                elem.InnerText = objectProperty.Value.ToString();
                myObjectElement.AppendChild(elem);
            }
        }
        rootElement.AppendChild(myObjectElement);
    }

1 个答案:

答案 0 :(得分:0)

XML规范仅允许文档中的单根元素document.AppendChild(elemRoot)方法中的AddNodeToXmlDocument()行抛出异常,因为之前已在SaveToFile()方法中创建了根元素:

.....
XmlElement elemRoot = xmlDoc.CreateElement("Orders");
xmlDoc.AppendChild(elemRoot);
.....

不清楚您尝试对错误的行做什么,也许您想要将elemRoot附加到先前创建的根元素上:

.....
var elemRoot = document.CreateElement(match.Value.Substring(7));
document.DocumentElement.AppendChild(elemRoot);
.....