**<Content>
<UId>1</UId>
<FileName>Calculator.txt</FileName>
<Image>1.jpg<Image/>
<FullPath>1</FullPath>
<FullPath>2</FullPath>
<FullPath>3</FullPath>
</Content>**
上記のXMLのように出力します。そのために私は以下のコードを書いています。既存のXML文書にfullpathが存在する場合は追加しないでください。ただし、以下のコードを使用するとXMLが正しく記述されません。 2つのコンテンツノードが追加されます。XML要素ノードが2回追加されます
string fullPath="1$2$3";
List<string> nodesToBeAdded = fullPath.Split('$').ToList();
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(filePath);
XmlNode nodeContent = xmlDocument.CreateNode(XmlNodeType.Element, "Content", null);
XmlNode nodeUID = xmlDocument.CreateNode(XmlNodeType.Element, "UId", null);
nodeUID.InnerText = value.UId;
XmlNode nodeFileName = xmlDocument.CreateNode(XmlNodeType.Element, "FileName", null);
nodeFileName.InnerText = value.FileName;
XmlNode nodeImage = xmlDocument.CreateNode(XmlNodeType.Element, "Image", null);
nodeImage.InnerText = value.Image;
for (int i = 0; i < nodesToBeAdded.Count - 1; i++)
{
XmlNode nodeFullPath = xmlDocument.CreateNode(XmlNodeType.Element, "FullPath", null);
nodeFullPath.InnerText = nodesToBeAdded[i];
if (xmlDocument.SelectNodes(string.Concat("//", "Content", '/', "FullPath", "[text()='" + nodesToBeAdded[i] + "']")).Count == 0)
{
nodeContent.AppendChild(nodeUID);
nodeContent.AppendChild(nodeFileName);
nodeContent.AppendChild(nodeImage);
nodeContent.AppendChild(nodeFullPath);
}
}//add parent node to document
xmlDocument.DocumentElement.AppendChild(nodeContent);
xmlDocument.Save(filePath);
出力:
<Content>
<UId>1</UId>
<FileName>Calculator.txt</FileName>
<Image>1.jpg</Image>
<FullPath>1</FullPath>
</Content>
<Content />
<Content />
<Content />
<Content />
LINQ to XMLを使用すると、はるかに簡単になります。 – Aybe
^^参照:https://msdn.microsoft.com/en-us/library/mt693076.aspx – Fildor