如何更改硬编码的XML文件的innertext? [英] How to change the innertext from an XML file hardcoded?

查看:92
本文介绍了如何更改硬编码的XML文件的innertext?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





编辑 - 重新调整我的问题并更改代码



我想通过硬编码从我的xml文件中更改一些innertext。但我磕磕绊绊地写了一条错误消息,说明代码中有不可读的字符。错误是在XmlDocument行上引发的。

我还尝试添加一个XmlTextReader来读取所选的XML文件,就像我在richTextbox中显示的那样,内存未填充不再有内容了。所以按钮btnMakeNegative通常不知道该怎么做。因此,我们需要读出richtextbox中的内容。但即使在那里我也得到了发现奇怪字符的错误消息。



主要用途:

点击按钮1加载Xml目录X中的文件,从列表中选择文件。

在richTextBox中显示

单击第二个按钮更改特定节点上的内部文本

点击第三个按钮将更改保存在特定目录中并给它原始名称+ - NEG。



提前致谢。



编辑2 - 找到错误的原因但不知道如何处理它。



Hi,

EDIT - refrasing my question and changing the code

I would like to change some innertext from my xml files by hardcoding it. But I'm stumbling on an error message that says that there are unreadable characters in the code. The error is thrown on the XmlDocument line.
I've also tried to add an XmlTextReader to read the selected XML file as I thought after it has been showed in the richTextbox, the memory isn't filled anymore with the content. So the button btnMakeNegative normally doesn't know what to make negative. Therefore we need to read out what's IN the richtextbox. But even there I'm getting the errormessage that strange characters were found.

Major purpose:
Click on button 1 to load an Xml file from directory X and choose the file out of a list.
Show this in a richTextBox
Click on a second button to change inner text on particular nodes
click on a third button to save the changes in a particular directory and give it the original name + "- NEG".

Thanks in advance.

EDIT 2 - Found the reason of the error but don't know how to handle it.

ok, I have found over which weird characters the code is stumbling but I can't fix it. Apparently, the xml file that I've opened with my button_click is read as a kind of HTML instead of an xml file. After initiating the XmlReader the reader can't figure out the backslashes and the backslashes+n in the file. when reading it it looks like this:

Hide   Copy Code
"<?xml version=\"1.0\"?>\n<PrepaymentGridfeeDataByServiceDeliveryPoint xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"un:unece:260:data:EEM:02-02-PrepaymentGridfeeDataByServiceDeliveryPoint\">\n  <HeaderBEEnergyDocument>\n    <Identification>45071dc8-558d-439a-8f0a-88ae73a74910</Identification>\n    <DocumentType listAgencyIdentifier=\"6\">386</DocumentType>\n    <Creation>2016-06-14T12:31:58.0+01:00</Creation>\n    <SenderBEEnergyParty>\n      <Identification schemeAgencyIdentifier=\"9\">5414488009809</Identification>\n    </SenderBEEnergyParty>\n    <RecipientBEEnergyParty>\n      <Identification schemeAgencyIdentifier=\"9\">0000000000000</Identification>  \n    </RecipientBEEnergyParty>\n    <IssuerBEEnergyParty>\n      <Identification schemeAgencyIdentifier=\"9\">5414488009809</Identification>\n    </

Notice the backslashes? They should be in the opposite way for an xml. And why the hell are there spaces in this file? Really weird!

So a solution would be that when I open openFileDialog1 I find a way to make him read the text in XML and not in PlainText. Is there a way to do this? Or should I need to give up the openFileDialog toolbox for this issue? what to use instead then?





我尝试过的事情:



Xml文件看起来像这样(它是部分的,但整个文档中的节点是相同的:root - parentnode -childnode( - 子子节点)有或没有属性:



What I have tried:

Xml file looks like this (it's partial but the nodes are the same in the whole document: root - parentnode -childnode (- subchildnode) with or without attributes:

<?xml version="1.0"?>
<AnXMLTestFile xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="un:unece:260:data:EEM:AnXMLTestFile">
  <HeaderBEDocument>
    <Identification>45071dc8-558d-439a-8f0a-88ae73a74910</Identification>
    <DocumentType listAgencyIdentifier="6">386</DocumentType>
    <Creation>2016-06-14T12:31:58.0+01:00</Creation>
    <SenderBEParty>
      <Identification schemeAgencyIdentifier="9">1234567890123</Identification>
    </SenderBEParty>
    <RecipientBEParty>
      <Identification schemeAgencyIdentifier="9">1234567890123</Identification>  
    </RecipientBEParty>
    <IssuerBEParty>
      <Identification schemeAgencyIdentifier="9">1234567890123</Identification>
    </IssuerBEParty>
    <AddresseeBEParty>
      <Identification schemeAgencyIdentifier="9">1234567890123</Identification>
    </AddresseeBEParty>
    <DocumentStructureRevision>02-02.001</DocumentStructureRevision>
  </HeaderBEDocument>
</AnXMLTestFile>





代码如下:



Code is as such:

    public partial class frmEditXML : Form
    {
        //get files from directory
        string[] path = Directory.GetFiles(@"C:\Users\decraiec\Documents\A_Automated", "*.XML");

        public frmEditXML()
        {
            InitializeComponent();
        }

        private void btnSelectFile_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "xml files|*.xml|All files|*.*";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    richTextBox1.LoadFile(openFileDialog1.FileName, RichTextBoxStreamType.PlainText);
                }
                catch (Exception exc)
                {
                    MessageBox.Show("An error occured: " + System.Environment.NewLine + exc.ToString() + System.Environment.NewLine);
                    throw;
                }
            }
        }

        private void btnMakeNegative_Click(object sender, EventArgs e)
        {
<pre> //Read selected file. For this create a reader.
            string _input = richTextBox1.Text;
            // You can pre-check the entire text by checking each character.
            // Though not totally efficient it does work.
            List<string> invalidChars = new List<string>();

            // You can change the loop to be able to replace the invalid characters if you like. This is an exampled to see what characters are bad.
            foreach (char ch in _input)
            {
                if (!XmlConvert.IsXmlChar(ch))
                {
                    invalidChars.Add(ch.ToString());
                }
            }
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreWhitespace = true;
            XmlTextReader reader = new XmlTextReader(_input); /*always error message*/
            XmlDocument doc = new XmlDocument();
            doc.Load(_input);
            XmlNodeList nodeList = doc.DocumentElement.SelectNodes("/AnXMLTestFile/");
            //find the node to change the content
            //if node is not present, do nothing
            foreach (XmlNode xNode in doc)
            {
                if (xNode.ParentNode.Attributes["HeaderBEDocument"].Value != "")
                {
                    doc.SelectSingleNode("Identification").InnerText = "string";
                    doc.SelectSingleNode("SCI").InnerText = "string";
                    doc.SelectSingleNode("ReferenceType").InnerText = "string";
                    doc.SelectSingleNode("CCType").InnerText = "AA";
                }
                else { } //do nothing
            }
        }

        private void btnSavechanges_Click(object sender, EventArgs e)
        {
            if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                File.WriteAllText(saveFileDialog1.FileName, richTextBox1.Text);
            }
        }

推荐答案

反斜杠问题只是在查看调试器中的字符串。它显示了您需要在C#代码中键入的字符串;字符串中实际不存在反斜杠, \ n 字符实际上是换行符(ASCII代码10)



你从新的XmlTextReader(_input)收到错误完全相同的原因您从 doc.Load(_input)收到错误 - 两种方法都希望 XML文件的路径,但是您正在传入< b>一串XML数据。



正如昨天所说,你需要更改代码才能使用 doc .LoadXml(_input),或者将 StringReader 传递给 XmlTextReader 构造函数。 />
The backslash issue is simply that you are looking at the string in the debugger. It shows the string as you would need to type it in your C# code; the backslashes are not actually present in the string, and the \n characters are actually newline characters (ASCII code 10).

You're getting an error from new XmlTextReader(_input) for exactly the same reason that you're getting an error from doc.Load(_input) - both methods expect the path to an XML file, but you are passing in a string of XML data.

As you were told yesterday, you need to change your code to use the doc.LoadXml(_input), or pass a StringReader to the XmlTextReader constructor.
private void btnMakeNegative_Click(object sender, EventArgs e)
{
    var doc = new XmlDocument();
    
    // Either:
    doc.LoadXml(richTextBox1.Text);
    
    // or:
    using (var input = new StringReader(richTextBox1.Text))
    using (var reader = XmlReader.Create(input))
    {
        doc.Load(reader);
    }
    
    ...
}


您可以使用XmlDocument读取xml字符串,但必须使用LoadXml(selectedFile)。



此外,如果您的富文本框不包含xml开始标记,则必须将其插入文本的开头。



除此之外,你的循环应检查ParentNode和Attributes是否为null。





You can read xml strings with XmlDocument but you must use LoadXml(selectedFile).

Also if your rich text box does not include the xml beginning tag, you must insert that to the beginning of the text.

In addition to that, your loop should check ParentNode and Attributes for null.


private void btnMakeNegative_Click(object sender, EventArgs e)
        {
            //Read selected file
            string selectedFile = richTextBox1.Text;//==>this was the reason of the error message
            XmlDocument doc = new XmlDocument();
            

            // Or just use the below code to remove them.
            StringBuilder newString = new StringBuilder();
            char ch;
        
            for (int i = 0; i < selectedFile.Length; i++)
            {
        
                ch = selectedFile[i];              
                if (XmlConvert.IsXmlChar(ch)) {
                    newString.Append(ch);
                }
            }

            selectedFile = newString.ToString();

            // The below change will build the XmlNode tree
            // An error will occur still if the xml is not formatted correctly.
            doc.LoadXml(selectedFile);


            //find the node to change the content
            //if node is not present, do nothing
            foreach (XmlNode xNode in doc)
            {            
                // change values
            }
        }


这与类型'system.argumentexception'的未处理异常完全相同发生在mscorlib.dll中的附加信息:路径中的非法字符。 [ ^ ]。您正在将XML文本读入RichEdit控件,稍后尝试将该文本用作文件名来存储更新的文本。您需要使用与最初读取数据相同的文件名,或者更好的是使用新文件名,以便不覆盖原始文件。
This is exactly the same issue as An unhandled exception of type 'system.argumentexception' occurred in mscorlib.dll additional information: illegal characters in path.[^]. You are reading XML text into a RichEdit control, and later trying to use that text as a file name to store the updated text. You need to use the same filename as you originally read the data from, or better still, a new filename in order not to overwrite the original.


这篇关于如何更改硬编码的XML文件的innertext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆