C#中以编程方式创建的XML缩进

时间:2010-01-27 15:00:34

标签: c# xml

我有一个XmlWriter如下

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.NewLineHandling = NewLineHandling.Entitize;
using (XmlWriter currentWriter = XmlWriter.Create(filePath, settings))
{
    workingXmlDocument.WriteTo(currentWriter);
    currentWriter.Flush();
} // using (XmlWriter xw = XmlWriter.Create(FilePath))

我已经以编程方式创建了一个我正在尝试使用它编写的Xml文档,它写得很好,除了我有一个在循环中创建的元素块并且它将所有这些元素放在一行上。如果你需要查看程序中的任何其他代码,请告诉我,我可以把它放在这里。我欢迎任何想法,即使它们不是完整的解决方案。

更新 - 问题发生的完整方法

private void XMLReaderUtil(string filePath)
    {
        XDocument workingXmlDocument;

        using (XmlReader currentReader = XmlReader.Create(filePath))
        {

            workingXmlDocument = XDocument.Load(currentReader);

            foreach (KeyValuePair<string, string> currentIteration in logDataRaw)
            {
                FileInfo currentEntry = new FileInfo(currentIteration.Value);

                string testString = currentEntry.Directory.Name;

                if (testString.Contains(" ")) { testString = testString.Replace(" ", "_"); }

                IEnumerable<XElement> list = from XElement e in workingXmlDocument.Descendants(wixNS + testString)
                                             select e;

                DirectoryInfo temp = currentEntry.Directory;

                while (list.Count() == 0 && !temp.Name.Contains(":"))
                {
                    testString = temp.Name;

                    if (testString.Contains(" ")) { testString = testString.Replace(" ", "_"); }

                    list = from XElement e in workingXmlDocument.Descendants(wixNS + testString)
                           select e;
                    temp = temp.Parent;
                } // while (list.Count() == 0 && !temp.Name.Contains(":"))

                if (list.Count() == 0)
                {
                    IEnumerable<XElement> targetDirectory =
                        from XElement e in workingXmlDocument.Descendants(wixNS + "Directory")
                        where e.Attribute("Id").Value == "TARGETDIR"
                        select e;

                    var outXml = new XElement("root");
                    foreach (var item in targetDirectory)
                    {
                        item.Add(new XElement(
                             "Directory",
                             new XAttribute("new", 1)));

                        outXml.Add(item);
                    }

                    outXml.Save(@"c:\users\adkins\desktop\temp.wxs", SaveOptions.None);

                }
            } // foreach (KeyValuePair<string, string> kvp in xmlDataChanged)
            // return workingXmlDocument;
        } // using (XmlReader sr = XmlReader.Create(FilePath))

        IEnumerable<XElement> cleanup =
            from XElement e in workingXmlDocument.Descendants(wixNS + "Directory")
            select e;
        Collection<string> keep = new Collection<string>();
        XElement[] blah;
        blah = cleanup.ToArray();

        for (int i = 0; i < blah.Length; i++)
        {
            if (!keep.Contains(blah[i].Attribute("Id").Value))
            {
                keep.Add(blah[i].Attribute("Id").Value);
            }
            else
            {
                blah[i].Remove();
            }
        }

        workingXmlDocument.Save(filePath, SaveOptions.None);

        // XMLWriter attempt
        //XmlWriterSettings settings = new XmlWriterSettings();
        //settings.Indent = true;
        //settings.IndentChars = "\t";
        //settings.NewLineHandling = NewLineHandling.Entitize;
        //settings.NewLineChars = "\n";
        //settings.CloseOutput = true;
        //settings.Encoding = System.Text.Encoding.UTF8;
        //using (XmlWriter currentWriter = XmlWriter.Create(filePath, settings))
        //{
        //    workingXmlDocument.WriteTo(currentWriter);
        //    currentWriter.Flush();
        //} // using (XmlWriter xw = XmlWriter.Create(FilePath))

        //TextWriter test run - nothing changed
        //XmlTextWriter writer = new XmlTextWriter(filePath, System.Text.Encoding.UTF8);
        //writer.Formatting = Formatting.Indented;
        //writer.IndentChar = '\t';
        //writer.Indentation = 1;

        //workingXmlDocument.WriteTo(writer);
        //writer.Flush();
        //writer.Close();

    }

这是完整的问题方法。它包括我尝试各种形式的文件保存。由于我努力解决这个问题以及在遇到这个问题之前遇到的问题,这是一个完整的混乱。任何帮助将不胜感激!

变量“logDataRaw”是一个字典,包含文件名和存储位置的路径。如果您需要任何其他说明,请告诉我。

4 个答案:

答案 0 :(得分:2)

问题在于我是通过XMLReader加载XML文件的。一旦我删除了它,并将其直接加载到我的XDocument中,而不是一切正常。

答案 1 :(得分:1)

为什么不使用XElement.Save()而不是XmlWriter?

http://msdn.microsoft.com/en-us/library/bb538458.aspx

编辑:

我刚刚运行了以下代码

        var xml = new XElement("root",
                               new XElement("node",
                                            new XAttribute("index", 1)
                                ),
                               new XElement("node",
                                            new XAttribute("index", 2)
                                ),
                               new XElement("node",
                                            new XAttribute("index", 3)
                                ),
                               new XElement("node",
                                            new XAttribute("index", 4)
                                )
            );

        IEnumerable<XElement> ieXml =
            from XElement e in xml.Elements()
            select e;

        var outXml = new XElement("root");
        foreach (var item in ieXml)
        {
            item.Add(new XElement(
                 "Directory",
                 new XAttribute("new", 1)));

            outXml.Add(item);
        }


        outXml.Save(@"d:\foo.xml", SaveOptions.None);

,结果格式化

<?xml version="1.0" encoding="utf-8"?>
<root>
  <node index="1">
    <Directory new="1" />
  </node>
  <node index="2">
    <Directory new="1" />
  </node>
  <node index="3">
    <Directory new="1" />
  </node>
  <node index="4">
    <Directory new="1" />
  </node>
</root>

我不知道你在做什么不同,但这很有效。

答案 2 :(得分:0)

您可能只需要使用带有默认编码的XmlTextWriter而不是XmlWriter,并将Writer对象的Formatting属性设置为Formatting.Indented

答案 3 :(得分:0)

如果有人使用XDocument并且仍然存在将XML保存到文件并使用正确缩进的问题,这可能对您有所帮助,它对我有用:

  1. 除了Chad的回答,我还必须在指定XElement名称时使用XName.Get(...):

    var xdoc = new XDocument(
                new XDeclaration("1.0", "utf-8", "yes"),
                new XElement(XName.Get("TranslationContainer"),
                             new XElement(XName.Get("Translations"))));
    
  2. 检查您是否有格式良好的xml(xml标签外没有文字)

  3. 祝你好运。