Замена значений, хранящихся в файле, значениями в объекте C# - PullRequest
0 голосов
/ 28 мая 2020
• 1000 Мне трудно заменить все такие значения сразу, так как я не могу применить оператор &&.

Вот мой код, очень благодарен за помощь

    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; }

}

Ответы [ 4 ]

1 голос
/ 28 мая 2020

Я бы предложил использовать конструктор строк, например:

public static string updatedDocu(string intialDocument, Student student)
        {
            return new StringBuilder(initialDocument)
                       .Replace("{studentName}", student.Name)
                       .Replace("{studentAge}", student.Age)
                       .ToString();
        }
1 голос
/ 28 мая 2020

Вам нужно заменить

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

на

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

, это будет работать. Исправьте орфографическую ошибку объекта student ( student ) на student

0 голосов
/ 28 мая 2020

Я не знаю, нужен ли вам этот подход, но вы можете автоматизировать процесс с использованием отражения, чтобы получить свойство из объекта на основе имени свойства, указанного в XML. Обратите внимание, что я не проверяю, существует ли свойство у объекта (в вашем случае - Student).

var xmlstr = @"<?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>";
XNamespace ns = "http://www.w3.org/2000/svg";
var xml = XElement.Parse(xmlstr);
var student = new Student { Name = "Steve", Age = "30" };
var type = student.GetType();
foreach(var text in xml.Elements(ns + "text"))
{
    // Get the name of the property we need to find in Student
    var prop_name = Regex.Match(text.Value, "[A-Z][a-z]+(?=})").Value;
    // Get the property on Student object
    var prop = type.GetProperty(prop_name);
    // Get the value of the propery on Student object
    var prop_val = prop.GetValue(student) as string;
    // Replace value of <text> element in XML 
    text.Value = prop_val;
}
0 голосов
/ 28 мая 2020

Попробуйте следующее 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);



        }
    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...