用对象C#中的值替换存储在文件中的值

问题描述 投票:0回答:3

我有一个如下定义的svg文件,

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<svg width="200mm" height="300mm"
    xmlns="http://www.w3.org/2000/svg" dominant-baseline="hanging">
    <text x="139.85mm" y="1.85mm" font-size="12pt">"studentName"</text>
    <text x="142.05mm" y="289.72mm" font-size="12pt">"studentAge"</text>
</svg>

我编写了一个程序,用存储在程序运行时中的实际值替换“”中存储的值,例如“ studentName”,但是我发现很难一次替换所有这些值,因为我无法应用&&运算符。

到目前为止,这是我的代码,非常感谢您的帮助

    class Program
    {
        static void Main(string[] args)
        {
            Student student = new Student();

            student.Name = "Max";
            student.Age = "10";


            string file = File.ReadAllText(@"D:\Del\structure.svg");
            updatedDocu(file, student);

        }


        public static string updatedDocu(string intialDocument , Student studemt)
        {

            string updatedDoc = intialDocument.Replace("{studentName}", studemt.Name) && intialDocument.Replace("{studentAge}",studemt.Age);
            return updatedDoc;

        }
    }
}

public class Student
{
    public Student()
    {

    }

    public string Name{ get; set; }
    public string Age { get; set; }

}

c# .net xml variables
3个回答
1
投票

您需要更换

string updatedDoc = intialDocument.Replace("{studentName}", studemt.Name) && intialDocument.Replace("{studentAge}",studemt.Age);

with

string updatedDoc = intialDocument.Replace("\"studentName\"", studemt.Name).Replace("\"studentAge\"",studemt.Age);

它将起作用。请将学生对象(studemt)的拼写错误更正为student


1
投票

例如,我建议使用stringbuilder:

public static string updatedDocu(string intialDocument, Student student)
        {
            return new StringBuilder(initialDocument)
                       .Replace("{studentName}", student.Name)
                       .Replace("{studentAge}", student.Age)
                       .ToString();
        }

0
投票

尝试以下xml linq:

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;


namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            XNamespace ns = doc.Root.GetDefaultNamespace();

            Dictionary<string, XElement> dict = doc.Descendants(ns + "text")
                .GroupBy(x => ((string)x).Replace("\"",""), y => y)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());

            XElement studentName = dict["studentName"];
            studentName.SetValue("John");

            XElement studentAge = dict["studentAge"];
            studentAge.SetValue(20);



        }
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.