Xml元素节点附加两次

时间:2017-02-24 12:19:14

标签: c# .net xml

 **<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下面的代码会被错误地写入。添加了两个内容节点。

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 />

3 个答案:

答案 0 :(得分:2)

我不确定您编写xml的规则,但我可以看到您必须编写多个内容并且完整路径无法重复相同内容 ,对吗?

因此,我可以看到代码中的 if语句负责生成空&lt; content /&gt; 标记,因为当您使用指令时< / p>

if (xmlDocument.SelectNodes(string.Concat("//", "Content", '/', "FullPath", "[text()='" + nodesToBeAdded[i] + "']")).Count == 0)
{
    nodeContent.AppendChild(nodeUID);
    nodeContent.AppendChild(nodeFileName);
    nodeContent.AppendChild(nodeImage);
    nodeContent.AppendChild(nodeFullPath);
}

你将寻找任何具有 text = nodesToBeAdded [i] 的完整路径,并且在第一个循环之后,你的条件if (xmlDocument.SelectNodes(string.Concat("//", "Content", '/', "FullPath", "[text()='" + nodesToBeAdded[i] + "']")).Count == 0)将始终返回true,因此代码可以重新添加所有节点上的元素将不会被执行。

我在您的代码中做了一些修复,允许检查当前内容,见下文:

 static void Main(string[] args)
 {
        string filePath = "D:\\teste.xml";
        string fullPath = "1$2$3";
        List<string> nodesToBeAdded = fullPath.Split('$').ToList();

        XmlDocument xmlDocument = new XmlDocument();

        xmlDocument.Load(filePath);

        for (int item = 1; item <= 3; item++)
        {
            XmlNode nodeContent = xmlDocument.CreateNode(XmlNodeType.Element, "Content", null);

            XmlNode nodeUID = xmlDocument.CreateNode(XmlNodeType.Element, "UId", null);
            nodeUID.InnerText = item.ToString();//value.UId;

            XmlNode nodeFileName = xmlDocument.CreateNode(XmlNodeType.Element, "FileName", null);
            nodeFileName.InnerText = item + "-Calculator.txt";// value.FileName;

            XmlNode nodeImage = xmlDocument.CreateNode(XmlNodeType.Element, "Image", null);
            nodeImage.InnerText = item + "-Image.jpg";//value.Image;

            for (int i = 0; i < nodesToBeAdded.Count; i++)
            {
                XmlNode nodeFullPath = xmlDocument.CreateNode(XmlNodeType.Element, "FullPath", null);
                nodeFullPath.InnerText = nodesToBeAdded[i];

                if (nodeContent.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("D:\\teste.xml");
    }

和结果

"<?xml version="1.0" encoding="utf-8"?>
    <root>
      <Content>
        <FullPath>1</FullPath>
        <FullPath>2</FullPath>
        <UId>1</UId>
        <FileName>1-Calculator.txt</FileName>
        <Image>1-Image.jpg</Image>
        <FullPath>3</FullPath>
      </Content>
      <Content>
        <FullPath>1</FullPath>
        <FullPath>2</FullPath>
        <UId>2</UId>
        <FileName>2-Calculator.txt</FileName>
        <Image>2-Image.jpg</Image>
        <FullPath>3</FullPath>
      </Content>
      <Content>
        <FullPath>1</FullPath>
        <FullPath>2</FullPath>
        <UId>3</UId>
        <FileName>3-Calculator.txt</FileName>
        <Image>3-Image.jpg</Image>
        <FullPath>3</FullPath>
      </Content>
    </root>"

我希望它可以帮到你。

答案 1 :(得分:0)

假设你的XML看起来像这样:

<root>
    <Content>
        <UId>1</UId>
        <FileName>Calculator.txt</FileName>
        <Image>1.jpg</Image>
        <FullPath>1</FullPath>
        <FullPath>2</FullPath>
        <FullPath>3</FullPath>
    </Content>
    <Content>
        <UId>2</UId>
        <FileName>Calculator2.txt</FileName>
        <Image>1.jpg</Image>
        <FullPath>1</FullPath>
        <FullPath>2</FullPath>
        <FullPath>3</FullPath>
    </Content>
</root>

您可以使用此http://xmltocsharp.azurewebsites.net/

   /* 
    Licensed under the Apache License, Version 2.0

    http://www.apache.org/licenses/LICENSE-2.0
    */
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Xml2CSharp
{
    [XmlRoot(ElementName="Content")]
    public class Content {
        [XmlElement(ElementName="UId")]
        public string UId { get; set; }
        [XmlElement(ElementName="FileName")]
        public string FileName { get; set; }
        [XmlElement(ElementName="Image")]
        public string Image { get; set; }
        [XmlElement(ElementName="FullPath")]
        public List<string> FullPath { get; set; }
    }

    [XmlRoot(ElementName="root")]
    public class Root {
        [XmlElement(ElementName="Content")]
        public List<Content> Content { get; set; }
    }

}

您可以阅读并生成XML:

// READ
var data = System.IO.File.ReadAllText(@"C:\temp\file.xml");
Root root;

var serializer = new XmlSerializer(typeof(Root));

using (var stream = new StringReader(data))
using (var reader = XmlReader.Create(stream))
{
    root = (Root)serializer.Deserialize(reader);
}

// WORK ON YOUR OBJECT.
// TODO ...

// WRITE
//var root = new Root();
root.Content = new List<Content>();
root.Content.Add(new Content { UId = "1", FileName = "file1.jpg" });
root.Content.Add(new Content { UId = "2", FileName = "file2.jpg" });

//var serializer = new System.Xml.Serialization.XmlSerializer(typeof(Root));
serializer.Serialize(File.Create(@"C:\temp\file1.xml"), root);

OR

你可以用这个: Visual Studio -> Edit -> Paste as XML

将生成此代码:

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class root
{

    private rootContent[] contentField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("Content")]
    public rootContent[] Content
    {
        get
        {
            return this.contentField;
        }
        set
        {
            this.contentField = value;
        }
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class rootContent
{

    private byte uIdField;

    private string fileNameField;

    private string imageField;

    private byte[] fullPathField;

    /// <remarks/>
    public byte UId
    {
        get
        {
            return this.uIdField;
        }
        set
        {
            this.uIdField = value;
        }
    }

    /// <remarks/>
    public string FileName
    {
        get
        {
            return this.fileNameField;
        }
        set
        {
            this.fileNameField = value;
        }
    }

    /// <remarks/>
    public string Image
    {
        get
        {
            return this.imageField;
        }
        set
        {
            this.imageField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("FullPath")]
    public byte[] FullPath
    {
        get
        {
            return this.fullPathField;
        }
        set
        {
            this.fullPathField = value;
        }
    }
}

然后您可以将其另存为XML文件,例如:

   var r = new root();
   r.Content = new rootContent[2];
   r.Content[0] = new rootContent() { UId = 1, FileName = "file1.jpg" };
   r.Content[1] = new rootContent() { UId = 2, FileName = "file2.jpg" };


   var serializer = new System.Xml.Serialization.XmlSerializer(typeof(root));
   serializer.Serialize(File.Create(@"C:\temp\file.xml"), r);

答案 2 :(得分:0)

如果我已正确理解您的情况,将func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) { switch item.title! { case "First": self.webView.load(URLRequest(url: url1)) case "Second": self.webView.load(URLRequest(url: url2)) default: self.webView.load(URLRequest(url: url3)) } } 移至xmlDocument.DocumentElement.AppendChild(nodeContent);块会有所帮助:

if

否则,将添加空节点。但我仍然不确定代码中的某些时刻,因此请考虑使用C#中提供的自动XML序列化工具。