同一属性中的多个值

时间:2014-01-28 04:31:51

标签: c# xml

我是新来的,我的英语不好!我希望你能理解我的意思!

主:

我有一个程序C#将xml转换为xml但结构不同!

这个矿:

<require_skill>
    <skillIds>236</skillIds>
    <skillIds>237</skillIds>
    <skillIds>238</skillIds>
    <skillIds>239</skillIds>
    <skillIds>240</skillIds>
    <skillIds>2039</skillIds>
    <skillIds>2811</skillIds>
</require_skill>

我希望这样做

<require_skill skillIds="236 237 238 239 240 2039 2811"/>

这是我的代码:

[XmlElement("require_skill", Form = XmlSchemaForm.Unqualified)]
    public RequireStigmaSkill[] require_skill;

[Serializable]
[XmlType(Namespace = "", AnonymousType = true)]
public class RequireStigmaSkill
{
    //[XmlAttribute]
    //public String skilllvl;

    [XmlElement("skillIds", Form = XmlSchemaForm.Unqualified)]
    public String[] skillIds;
}

在主程序中:

utility.Export<String>(item, "require_skill", requiredGen);
if (requiredGen.Count() > 0)
{
    List<RequireStigmaSkill> requiredArray = new List<RequireStigmaSkill>();
    foreach (string asName in requiredGen)
    {
        //asName as SkillStartname
        List<String> forThisName = new List<string>();
        foreach (ClientSkill skillGen in skills.SkillList)
        {
            if (skillGen.name.StartsWith(asName))
            {
                if (skillGen.name.StartsWith(asName))
                    forThisName.Add(skillGen.id);
            }
        }

        //Did it.
        var required = new RequireStigmaSkill();
        //required.skilllvl = "1";
        required.skillIds = forThisName.ToArray();
        requiredArray.Add(required);
    }
    i.stigma.require_skill = requiredArray.ToArray();
}

如何在同一属性中创建多个值?

1 个答案:

答案 0 :(得分:0)

我实际上无法理解您的主要代码,所以我尝试根据需要创建一个字符串。尝试将其映射到您的代码并尽可能进行必要的更改。以下是我所做的步骤:

  1. 创建了一个xml文件并将您的输入xml复制粘贴
  2. 加载xml文件并创建字符串。以下是相同的代码:

        XmlDocument doc = new XmlDocument();
        doc.Load("XMLFile1.xml");
        StringBuilder builder = new StringBuilder();
    
        foreach (XmlNode require_skill in doc.ChildNodes)
        {
            foreach (XmlNode skillIds in require_skill.ChildNodes)
            {
                builder.Append(skillIds.InnerText);
                builder.Append(" ");
            }
        }
    
        string attributeStr = builder.ToString().Substring(0, builder.Length - 1);
    
        string finalStr = "<require_skill skillIds=\"" + attributeStr + "\"\\>";
    
  3. 然后您可以使用“System.IO.File.WriteAllText”将此字符串写入文件

    System.IO.File.WriteAllText("filename.xml", finalStr);
    
  4. 希望这有帮助。