【问题标题】:writting multiple xml nodes in a single xml file在单个 xml 文件中写入多个 xml 节点
【发布时间】:2012-05-12 04:54:37
【问题描述】:

我有使用 LINQ to XML 的代码。我希望每次都将该 XElement 写入一个新的 XML 文件,以便其中的所有 XML 都存储在指定位置的 XML 文件中。

XElement xml = new XElement("contacts",
                    new XElement("contact", 
                        new XAttribute("contactId", "2"),
                        new XElement("firstName", "Barry"),
                        new XElement("lastName", "Gottshall")
                    ),
                    new XElement("contact", 
                        new XAttribute("contactId", "3"),
                        new XElement("firstName", "Armando"),
                        new XElement("lastName", "Valdes")
                    )
                );


Console.WriteLine(xml);

我希望追加 xml 变量并向其中添加更多节点,我尝试了以下代码但无法获得它,我希望将我在 EveryComment List 中获得的所有 xml 都写下来

 XElement xml;
                    foreach (string Dcomment in EveryComment) 
                    {
                        string commentDetail = "http://www.edmunds.com" + Dcomment;
                        WebClient wc1 = new WebClient();
                        try { 
                            string comm = wc1.DownloadString(commentDetail);
                            string[] time_sep = { @"<time itemprop=""dtreviewed"" datetime=", "</time></div>" };
                            string[] car_split = {@"<span itemprop=""itemreviewed"">",@"</span><br/>        <div class=""header-5"">Review</div>"};
                            string[] name_comment_split = {@"<div class=""crr_by"">By <strong itemprop=""reviewer"">","</strong> on <time itemprop=",@"<div class=""header-5"">Review</div>        <span itemprop=""description"">",@"<div class=""header-5"">Favorite Features</div>" };
                            string[] get_name_comment = comm.Replace("\n", "").Replace("\t", "").Split(name_comment_split, StringSplitOptions.None);
                            string[] get_car_name = comm.Replace("\n","").Replace("\t","").Split(car_split, StringSplitOptions.None);
                            //CAR NAME AT 1 INDEX
                            string perfor,comfi,fuel,fun,interi,exteri,made,reliable;
                            string[] get_time = comm.Split(time_sep, StringSplitOptions.None);//TIME AT 1TH INDEX
                            comm = comm.Replace(@"""", "").Replace("\n"," ").Replace("\t"," ").Replace(" ","").Replace("\r","");
                            //HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                            //doc.LoadHtml(comm);
                            //var links = doc.DocumentNode.Name="span".Select(n => n.["href"].Value).ToArray();
                            string[] comm_split = { "Performance<hr/><spanclass=ratingtitle=", "Comfort<hr/><spanclass=ratingtitle=", "FuelEconomy<hr/><spanclass=ratingtitle=", "Fun-to-Drive<hr/><spanclass=ratingtitle=", "InteriorDesign<hr/><spanclass=ratingtitle=", "ExteriorDesign<hr/><spanclass=ratingtitle=", "BuildQuality<hr/><spanclass=ratingtitle=", "Reliability</div><spanclass=rating-bigtitle=","<divclass=header-5>FavoriteFeatures</div>", "<divclass=header-5>SuggestedImprovements</div>" };
                            string[] features = comm.Split(comm_split, StringSplitOptions.None);
                            if (features[1].ElementAt(1) == '.')
                            {

                                perfor = features[1].Substring(0, 3);
                            }
                            else
                                perfor = features[1].Substring(0, 1);
                            if (features[2].ElementAt(1) == '.')
                            {

                                comfi = features[2].Substring(0, 3);
                            }
                            else
                                comfi = features[2].Substring(0, 1);
                            if (features[3].ElementAt(1) == '.')
                            {

                                fuel = features[3].Substring(0, 3);
                            }
                            else
                                fuel = features[3].Substring(0, 1);
                            if (features[4].ElementAt(1) == '.')
                            {

                                fun = features[5].Substring(0, 3);
                            }
                            else
                                fun = features[5].Substring(0, 1);
                            if (features[6].ElementAt(1) == '.')
                            {

                                interi = features[6].Substring(0, 3);
                            }
                            else
                                interi = features[6].Substring(0, 1);

                            if (features[7].ElementAt(1) == '.')
                            {

                                exteri = features[7].Substring(0, 3);
                            }
                            else
                                exteri = features[7].Substring(0, 1);

                            if (features[8].ElementAt(1) == '.')
                            {

                                reliable = features[8].Substring(0, 3);
                            }
                            else
                                reliable = features[8].Substring(0, 1);


               xml = new XElement("DOC", 
                    new XAttribute("Relevance", c1.relevance),
                    new XElement("Date", get_time[1]),
                    new XElement("Author", get_name_comment[1]),
                    new XElement("Text", get_name_comment[3]),
                    new XElement("Favourite",features[9]),
                    new XElement("Peformance",perfor),
                    new XElement("Fuel",fuel),
                    new XElement("Fun",fun),
                    new XElement("Interior",interi),
                    new XElement("Exterior",exteri),
                    new XElement("Reliability",reliable)
                );
                       // xml = new XElement(get_car_name

                        }
                        catch (Exception ex) 
                        {
                        }
                    }

【问题讨论】:

  • 您想将此 xml 存储在一个文件中吗?
  • 您的问题是什么?什么不工作?
  • 我添加了更多代码我希望在每次迭代中连接 xml,在循环之后我会将它保存到文件中
  • @Robust 让我感到困惑的是,您的两个样本似乎无关。这里的实际问题是什么?只要大小不是很大,您就可以附加到 DOM。如果大小为 huuuuge,则 XmlWriter 是一个选项。哪个适用于您的场景?
  • 我在循环结束时将每个 xelemnt 都转换为字符串并继续连接该字符串,循环后我通过字符串编写器在 .xml 文件中写入

标签: c# c#-4.0 linq-to-xml


【解决方案1】:
xml.Save(path);

或者有没有更微妙的东西,这不是问题?

【讨论】:

  • 我添加了更多代码我希望在每次迭代中连接 xml,在循环之后我会将它保存到文件中
  • @RobustRob 由于需要单个外部根元素,您无法真正连接 xml 文档。这留下了 2 个选项:每次保存都重写 everything,或者:使用 XmlWriter 之类的东西写入仅转发流
  • 任何 hello world 示例都对我的案例非常有帮助
【解决方案2】:

我是这样做的 我在循环结束时将每个 xelemnt 转换为字符串并继续连接该字符串,在循环之后我通过字符串编写器在 .xml 文件中写入

【讨论】:

    猜你喜欢
    • 2015-08-04
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多