2015-05-24 80 views
3

喜新的XElement我有一个XML文件:添加数据类型属性

<?xml version="1.0"?> 
<TreeList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <Columns> 
    <Column> 
     <ColumnName>123</ColumnName> 
     <ColumnType>Bound</ColumnType> 
    </Column> 
    </Columns> 
    <Nodes> 
    <Node Id="0" ParentId="-1"> 
     <NodeData> 
     <Cell xsi:type="xsd:string">Node1</Cell> 
     </NodeData> 
    </Node> 
    <Node Id="1" ParentId="0"> 
     <NodeData> 
     <Cell xsi:type="xsd:string">Node11</Cell> 
     </NodeData> 
    </Node> 
    </Nodes> 
</TreeList> 

,我需要增加新的XElement:

<Node Id="xx" ParentId="yy"> 
    <NodeData> 
    <Cell xsi:type="xsd:string">NewNode</Cell> 
    </NodeData> 
</Node> 

我的问题是,在 “XSI:类型=” XSD :?字符串的”的XElement的一部分,我怎么能设置XAttribute这样

我尝试以下操作:

public static void AdNewNode(string filePath, string id, string parentId, string value) 
    { 
     XElement xml = XElement.Load(filePath); 
     XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance"; 
     XNamespace xsd = "http://www.w3.org/2001/XMLSchema"; 
     XAttribute attribute1 = new XAttribute(xsd + "string", string.Empty); 
     XAttribute attribute2 = new XAttribute(xsi + "type", attribute1.ToString()); 

     XElement innerNode = new XElement("NodeData", 
         new XElement("Cell",attribute2, attribute1, value)); 
     XElement elemnet = new XElement("Node", new XAttribute("Id", id), new XAttribute("ParentId", parentId), innerNode); 

     xml.Add(elemnet); 
    } 

这是结果:

<Node Id="2" ParentId="1"> 
    <NodeData> 
    <Cell p3:type="p0:string=&quot;&quot;" p4:string="" xmlns:p4="http://www.w3.org/2001/XMLSchema" xmlns:p3="http://www.w3.org/2001/XMLSchema-instance">New Node</Cell> 
    </NodeData> 
</Node> 

有人能帮助我吗?

回答

2

"xsd:string"只是普通的字符串,所以你应该能够构建xsi:type属性,像这样:

XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance"; 
XAttribute attribute = new XAttribute(xsi+"type", "xsd:string"); 

然后添加attribute它是随随便便的父元素:

XElement innerNode = new XElement("NodeData", 
         new XElement("Cell", attribute, value)); 
XElement elemnet = new XElement("Node", 
         new XAttribute("Id", id), 
         new XAttribute("ParentId", parentId), 
         innerNode); 
+0

感谢的它的工作就像一个魅力。 – user3569465

+1

@ user3569465不客气。不要忘记[接受](http://stackoverflow.com/help/someone-answers)然后回答 – har07