簡體   English   中英

將 XML 內容從 TextBox 導出到 XML 文件

[英]Export an XML content from a TextBox into an XML file

我正在嘗試創建一個將 XML 文件導入到 TextBox 的應用程序,目的是編輯內容。 編輯后,用戶應該能夠保存文件的內容,但同時對其進行驗證。 例如,

<Person id="22">
    <Name gg="u">John</Name>
    <Surname>Jones</Surname>
    <PhoneNo>333333333111</PhoneNo>
    <Country>Germany</Country>
</Person>

如果用戶編輯了開始標簽“Name”,但忘記編輯結束標簽,則應該拋出異常。 我試過了

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(MyTextBox.Text);
xmlDoc.Save(fileName);

XmlElement DocRoot = xmlDoc.CreateElement("root");
DocRoot.InnerText = MyTextBox.Text;
xmlDoc.AppendChild(DocRoot);
xmlDoc.Save(fileName);

沒有一個工作。 我很感激任何幫助,謝謝!

我有這個解決方案,它似乎工作:) 根據 xsd 問題,我有一個通用的 XML。

try
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(MyTextBox.Text);
        XmlWriterSettings settings = new XmlWriterSettings
        {
        Indent = true
    };
    XmlWriter writer = XmlWriter.Create(fileName, settings);
    xmlDoc.Save(writer);
    MessageBox.Show("File overwritten to: " + fileName);
    }
    catch (Exception ex)
    {
    MessageBox.Show("The textbox content is wrong. ");
    }

似乎您正在嘗試檢查 XML 文本是否格式正確,而不是真的對某個定義有效。

要檢查 XML 文本是否格式正確,您可以嘗試解析它並驗證它是否包含任何錯誤。 這是一個嘗試這樣做的函數:

class Program
{
    static void Main(string[] args)
    {
        var result = ValidateXml("<Person id=\"22\"><Name>John<Name></Person>");
        if (!result.IsValid)
        {
            Console.WriteLine($"Line number: {result.Exception.LineNumber}");
            Console.WriteLine($"Line position: {result.Exception.LinePosition}");
            Console.WriteLine($"Message: {result.Exception.Message}");
        }

        // OUTPUT:
        // Line number: 1
        // Line position: 35
        // Message: The 'Name' start tag on line 1 position 28 does not match the end tag of 'Person'.Line 1, position 35.
    }

    static ValidationResult ValidateXml(string xml)
    {
        using (var xr = XmlReader.Create( new StringReader(xml)))
        {
            try
            {
                while (xr.Read())
                {
                }

                return ValidationResult.ValidResult;
            }
            catch (XmlException exception)
            {
                return new ValidationResult(exception);
            }
        }
    }

    public class ValidationResult
    {
        public static ValidationResult ValidResult = new ValidationResult();

        private ValidationResult()
        {
            IsValid = true;
        }

        public ValidationResult(XmlException exception)
        {
            IsValid = false;
            Exception = exception;
        }

        public bool IsValid { get; }

        public XmlException Exception { get;}
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM