Add new XElement with datatype attribute
Hi I have an xml file:
<?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>
and I need to add a new XElement:
<Node Id="xx" ParentId="yy">
<NodeData>
<Cell xsi:type="xsd:string">NewNode</Cell>
</NodeData>
</Node>
my problem is in the "xsi: type =" xsd: string "part of the XElement. How can I set the XAttribute like this?
I've tried the following:
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);
}
And this is the result:
<Node Id="2" ParentId="1">
<NodeData>
<Cell p3:type="p0:string=""" p4:string="" xmlns:p4="http://www.w3.org/2001/XMLSchema" xmlns:p3="http://www.w3.org/2001/XMLSchema-instance">New Node</Cell>
</NodeData>
</Node>
Can anyone help me?
+3
source to share
1 answer
"xsd:string"
is just a string, so you can construct an attribute xsi:type
like this:
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
XAttribute attribute = new XAttribute(xsi+"type", "xsd:string");
Then add attribute
a parent to it:
XElement innerNode = new XElement("NodeData",
new XElement("Cell", attribute, value));
XElement elemnet = new XElement("Node",
new XAttribute("Id", id),
new XAttribute("ParentId", parentId),
innerNode);
+2
source to share