开发者

Is it the Correct way to create an XML like this:

I want to create something like this at run-time:

  <CWS>
    <Case name="10-040-00022">
      <CaseDetailsSet>
        <CaseDetail title="Patient name" /> 
        <CaseDetail title="开发者_如何学JAVADate of birth" /> 
      </CaseDetailsSet>
    </Case>
  </CWS>

so I wrote something like this ( I wish to use DOM in .NET .. not the XMLWriter,etc)

    XmlDocument doc = new XmlDocument();

    XmlElement root = doc.CreateElement("CWS");
    XmlElement singleCase = doc.CreateElement("Case");

    root.AppendChild(singleCase);

    singleCase.SetAttribute("name", "10-040-00022");

    XmlElement CaseDetailsSet = doc.CreateElement("CaseDetailsSet");
    singleCase.AppendChild(CaseDetailsSet);

    XmlElement CaseDetail = doc.CreateElement("CaseDetail");
    CaseDetailsSet.AppendChild(CaseDetail);
    CaseDetail.SetAttribute("title", "Patient Name");

please have a look at it and tell me if I am oing something wrong , regardign the code I worte to create that structure above.

much appreciated.


Two things:

  1. You'll need to append the root to the XmlDocument.
  2. You need to add the second CaseDetail.

    XmlDocument doc = new XmlDocument();
    
    XmlElement root = doc.CreateElement("CWS");
    
    doc.AppendChild(root); // Append the root element to the XmlDocument
    
    XmlElement singleCase = doc.CreateElement("Case");
    
    root.AppendChild(singleCase);
    
    singleCase.SetAttribute("name", "10-040-00022");
    
    XmlElement CaseDetailsSet = doc.CreateElement("CaseDetailsSet");
    singleCase.AppendChild(CaseDetailsSet);
    
    XmlElement CaseDetail = doc.CreateElement("CaseDetail");
    CaseDetailsSet.AppendChild(CaseDetail);
    CaseDetail.SetAttribute("title", "Patient Name");
    
    // add the second case detail
    XmlElement CaseDetailDateOfBirth = doc.CreateElement("CaseDetail");
    CaseDetailsSet.AppendChild(CaseDetailDateOfBirth);
    CaseDetailDateOfBirth.SetAttribute("title", "Date of birth");
    


Just thought I'd show how to do this with Linq-to-XML

XElement doc = new XElement("CWS",
    new XElement("Case",
        new XAttribute("name", "10-040-00022"),
        new XElement("CaseDetailSet",
            new XElement("CaseDetail",
                new XAttribute("title", "Patient name")),
            new XElement("CaseDetail",
                new XAttribute("title", "Date of birth")))));


I don't see a problem with your code. If it creates the xml you want, it should be ok. There are many different ways of creating xml documents, yours seems to be okay.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜