2011-12-06 3 views
4

저는 Visual Web Developer 2008 Express Edition을 사용하고 있습니다. 저는 처음부터 익숙해졌습니다. 삽입하거나 데이터를 내 XML 컨트롤에 표시 할 수 있도록 XML 파일에 쓰려고합니다. 자, 여기서 내가하려고하는 것은 사용자가 텍스트 상자에 메시지를 입력 할 때마다 옵션을 저장하므로 명령 단추를 클릭하면 텍스트 메시지의 텍스트 메시지를 my xml의 모든 요소에 저장하려고합니다. 파일. 예를 들어, 내 xml 파일의 요소에 삽입하고 싶습니다. C# 또는 VB.Net 코드를 사용하여 어떻게합니까? 내 XML 파일을 내 C# 코드가 있지만 나를 위해 C# 코드가 작동하지 않습니다. 나는 C# 또는 vb.net 중 하나에 대한 코드가 필요합니다, 어느 쪽이든 나를 위해 작동합니다. 대단히 감사 드리며 공유 할 수있는 모든 도움에 깊이 감사드립니다.asp.net에서 기존 xml 파일에 데이터를 삽입하는 방법은 무엇입니까?

myxmlfile.xml

<?xml version="1.0" encoding="utf-8" ?> 
<comments> 
    <comment> 
     Your Comments Here: Please post your comments now. Thank you. 
    </comment> 
    <comment2> 
     Note: Please do not post any profane languages. 
    </comment2> 
    <comment3> 
     I don't like their service. It's too lousy. 
    </comment3> 
    <comment4> 
     Always be alert on your duty. Don't be tardy enough to waste your time. 
    </comment4> 
</comments> 

코드

protected void Button1_Click(object sender, EventArgs e) 
{ 
    System.Xml.Linq.XDocument mydoc = 
     new System.Xml.Linq.XDocument(
      new System.Xml.Linq.XDeclaration("1.0", "UTF-8", "yes"), 
      new System.Xml.Linq.XElement("comment", 
       new System.Xml.Linq.XComment(TextBox1.Text))); 

    mydoc.Save("myxmlfile.xml",System.Xml.Linq.SaveOptions .None); 
} 

답장을 보내 주셔서 대단히 @Joseph LeBrech 및 @AVD --Thank 당신. 이 코드는 myxmlfile에 새로운 루트 요소를 추가하므로 새로운 루트 요소가 myxmlfile을 XML에 표시하기 위해 내 xslt 파일에 포함되어 있지 않기 때문에 페이지를 다시로드 할 때 새 루트 요소가 내 xml 컨트롤에 표시되지 않는 것이 문제입니다 제어. myxmlfile에 새로운 루트 요소를 추가하고 싶지 않습니다. 텍스트 상자에서 입력 한 메시지를 요소 인 myxmlfile의 기존 요소에 삽입하여 myxmlfile을 표시 할 XML 컨트롤에 표시되도록 할 수 있습니다. 코드를 다시 수정할 수 있기를 바랍니다. 도와 주셔서 대단히 감사합니다. 나는 크게 그것을 평가했다.

+3

이렇게 주석 태그를 증가 시키면 안됩니다. 정렬을 위해'name' 또는'id' 속성이나'date'를 넣을 수는 있지만 태그를 증가 시키면 문제가 생깁니다. –

+0

이렇게 주석 태그를 사용하지 않는 이유 중 하나는 DTD에서 주석 태그를 설명 할 수있는 정상적인 방법이 없다는 것입니다. 주석 순서는 파일의 주석 순서에 의해 이미 암시되어 있습니다. –

+0

답변을 편집하여 회신하지 마십시오. 답변 아래에 "덧글 추가"를 사용하거나 질문을 편집하여 추가 정보를 제공하십시오. –

답변

5

당신은 XML 문서를 저장하는 MapPath를()를 사용하여 절대 파일 경로를 지정해야하고, comment2 .. 등

코드를 살펴 보자 comment1 같은 태그 이름을 증가하지 않습니다 -snippet :

protected void Button1_Click(object sender, EventArgs e) 
{ 
    string file = MapPath("~/comments.xml"); 

    XDocument doc; 

    //Verify whether a file is exists or not 
    if (!System.IO.File.Exists(file)) 
    { 
     doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), 
      new System.Xml.Linq.XElement("comments")); 
    } 
    else 
    { 
     doc = XDocument.Load(file); 
    } 

    XElement ele = new XElement("comment",TextBox1.Text); 
    doc.Root.Add(ele); 
    doc.Save(file); 
} 

편집 : 당신은 기존 XML 다음 문서하여 XDocument를 만들 필요로 <comment> 태그를 삽입합니다. 기존 문서를로드하고 루트에 새 요소를 추가하기 만하면됩니다.

protected void Button1_Click(object sender, EventArgs e) 
{ 
    string file = MapPath("~/myxmlfile.xml"); 
    XDocument doc = XDocument.Load(file); 

    XElement ele = new XElement("comment",TextBox1.Text); 
    doc.Root.Add(ele); 
    doc.Save(file); 
} 

<comment> 내부에 또 다른 <comment> 태그를 추가하려면 :

doc.Root.Element("comment").Value = TextBox1.Text; 
//doc.Root.Element("comment").Value += TextBox1.Text; //append text 
doc.Save(file); 

XML 문서 :

<?xml version="1.0" encoding="utf-8" ?> 
<comments> <!-- Root Node --> 
    <comment>First Child</comment> 
    <comment> <!-- Second Child --> 
    <comment>Nested</comment> 
    </comment> 
</comments> 
+0

@timmack - 편집 된 게시물을 확인하십시오. – adatapost

+0

@AVD ----------- 그래, 위의 코드는 여전히 myxmlfile에 새로운 루트 요소를 추가합니다. myxmlfile의 기존 요소에 데이터를 추가하거나 삽입하려고합니다. 위의 원래 myxml 파일을보십시오. 귀하의 의견 : 여기에 의견을 게시 해주십시오. 고맙습니다. timmack

+0

@AVD ----------- 좋아요, 위의 코드는 여전히 myxmlfile에 새로운 루트 요소를 추가합니다. myxmlfile의 기존 요소에 데이터를 추가하거나 삽입하려고합니다. 위의 원래 myxmlfile을 보시기 바랍니다. ' 귀하의 의견 : 제발 지금 의견을 게시하십시오. 고맙습니다.' 내부에있는 기존 요소에서 데이터를 삽입하여 데이터를 표시 할 수 있도록 XML 컨트롤에 표시 할 수 있습니다. 새 루트 요소를 추가하면 내 xslt 파일에 포함되어 있지 않으므로 xml 컨트롤에 표시되지 않습니다. 그게 가능하니? 고맙습니다. – timmack

2

myDoc.Element("comments").Add(new xElement("comment5") { Value = "put the value in here"});

1
XElement ele = new XElement("comment",TextBox1.Text); 
doc.Root.Element("comment").Add(ele); 
doc.Save(file); 

<comment> 태그의 텍스트 값을 바꾸려면 enter image description here

디자인 this.In 버튼 클릭 이벤트 같은 페이지는 다음 코드를

protected void btnInsert_Click(object sender, EventArgs e) 
    { 
     System.Xml.XmlDocument myXml = new System.Xml.XmlDocument(); 
     myXml.Load(Server.MapPath("InsertData.xml")); 
     System.Xml.XmlNode xmlNode = myXml.DocumentElement.FirstChild; 
     System.Xml.XmlElement xmlElement = myXml.CreateElement("entry"); 

     xmlElement.SetAttribute("Name", Server.HtmlEncode(txtname.Text)); 
     xmlElement.SetAttribute("Location", Server.HtmlEncode(txtlocation.Text)); 
     xmlElement.SetAttribute("Email", Server.HtmlEncode(txtemail.Text)); 
     xmlElement.SetAttribute("Gender", Server.HtmlEncode(ddlgender.SelectedItem.Text)); 

     myXml.DocumentElement.InsertBefore(xmlElement,xmlNode); 
     myXml.Save(Server.MapPath("InsertData.xml")); 

     BindData(); 

     lbldisplay.Text = "Record inserted into XML file successfully"; 
     txtname.Text = ""; 
     txtlocation.Text = ""; 
     txtemail.Text = ""; 
    } 

    private void BindData() 
    { 
     XmlTextReader xmlReader = new XmlTextReader(Server.MapPath("InsertData.xml")); 
     xmlReader.Close(); 
    } 

를 작성하고 또한 XML 파일에서 이벤트 태그를 넣어. 이제 응용 프로그램을 실행하고 출력을 확인하십시오.

관련 문제